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 |
|---|---|---|---|---|---|---|---|---|
// *** 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.Storage
{
/// <summary>
/// Properties of the blob container, including Id, resource name, resource type, Etag.
/// API Version: 2021-02-01.
/// </summary>
[AzureNativeResourceType("azure-native:storage:BlobContainer")]
public partial class BlobContainer : Pulumi.CustomResource
{
/// <summary>
/// Default the container to use specified encryption scope for all writes.
/// </summary>
[Output("defaultEncryptionScope")]
public Output<string?> DefaultEncryptionScope { get; private set; } = null!;
/// <summary>
/// Indicates whether the blob container was deleted.
/// </summary>
[Output("deleted")]
public Output<bool> Deleted { get; private set; } = null!;
/// <summary>
/// Blob container deletion time.
/// </summary>
[Output("deletedTime")]
public Output<string> DeletedTime { get; private set; } = null!;
/// <summary>
/// Block override of encryption scope from the container default.
/// </summary>
[Output("denyEncryptionScopeOverride")]
public Output<bool?> DenyEncryptionScopeOverride { get; private set; } = null!;
/// <summary>
/// Resource Etag.
/// </summary>
[Output("etag")]
public Output<string> Etag { get; private set; } = null!;
/// <summary>
/// The hasImmutabilityPolicy public property is set to true by SRP if ImmutabilityPolicy has been created for this container. The hasImmutabilityPolicy public property is set to false by SRP if ImmutabilityPolicy has not been created for this container.
/// </summary>
[Output("hasImmutabilityPolicy")]
public Output<bool> HasImmutabilityPolicy { get; private set; } = null!;
/// <summary>
/// The hasLegalHold public property is set to true by SRP if there are at least one existing tag. The hasLegalHold public property is set to false by SRP if all existing legal hold tags are cleared out. There can be a maximum of 1000 blob containers with hasLegalHold=true for a given account.
/// </summary>
[Output("hasLegalHold")]
public Output<bool> HasLegalHold { get; private set; } = null!;
/// <summary>
/// The ImmutabilityPolicy property of the container.
/// </summary>
[Output("immutabilityPolicy")]
public Output<Outputs.ImmutabilityPolicyPropertiesResponse> ImmutabilityPolicy { get; private set; } = null!;
/// <summary>
/// Returns the date and time the container was last modified.
/// </summary>
[Output("lastModifiedTime")]
public Output<string> LastModifiedTime { get; private set; } = null!;
/// <summary>
/// Specifies whether the lease on a container is of infinite or fixed duration, only when the container is leased.
/// </summary>
[Output("leaseDuration")]
public Output<string> LeaseDuration { get; private set; } = null!;
/// <summary>
/// Lease state of the container.
/// </summary>
[Output("leaseState")]
public Output<string> LeaseState { get; private set; } = null!;
/// <summary>
/// The lease status of the container.
/// </summary>
[Output("leaseStatus")]
public Output<string> LeaseStatus { get; private set; } = null!;
/// <summary>
/// The LegalHold property of the container.
/// </summary>
[Output("legalHold")]
public Output<Outputs.LegalHoldPropertiesResponse> LegalHold { get; private set; } = null!;
/// <summary>
/// A name-value pair to associate with the container as metadata.
/// </summary>
[Output("metadata")]
public Output<ImmutableDictionary<string, string>?> Metadata { get; private set; } = null!;
/// <summary>
/// The name of the resource
/// </summary>
[Output("name")]
public Output<string> Name { get; private set; } = null!;
/// <summary>
/// Specifies whether data in the container may be accessed publicly and the level of access.
/// </summary>
[Output("publicAccess")]
public Output<string?> PublicAccess { get; private set; } = null!;
/// <summary>
/// Remaining retention days for soft deleted blob container.
/// </summary>
[Output("remainingRetentionDays")]
public Output<int> RemainingRetentionDays { get; private set; } = null!;
/// <summary>
/// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts"
/// </summary>
[Output("type")]
public Output<string> Type { get; private set; } = null!;
/// <summary>
/// The version of the deleted blob container.
/// </summary>
[Output("version")]
public Output<string> Version { get; private set; } = null!;
/// <summary>
/// Create a BlobContainer 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 BlobContainer(string name, BlobContainerArgs args, CustomResourceOptions? options = null)
: base("azure-native:storage:BlobContainer", name, args ?? new BlobContainerArgs(), MakeResourceOptions(options, ""))
{
}
private BlobContainer(string name, Input<string> id, CustomResourceOptions? options = null)
: base("azure-native:storage:BlobContainer", 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:storage:BlobContainer"},
new Pulumi.Alias { Type = "azure-native:storage/v20180201:BlobContainer"},
new Pulumi.Alias { Type = "azure-nextgen:storage/v20180201:BlobContainer"},
new Pulumi.Alias { Type = "azure-native:storage/v20180301preview:BlobContainer"},
new Pulumi.Alias { Type = "azure-nextgen:storage/v20180301preview:BlobContainer"},
new Pulumi.Alias { Type = "azure-native:storage/v20180701:BlobContainer"},
new Pulumi.Alias { Type = "azure-nextgen:storage/v20180701:BlobContainer"},
new Pulumi.Alias { Type = "azure-native:storage/v20181101:BlobContainer"},
new Pulumi.Alias { Type = "azure-nextgen:storage/v20181101:BlobContainer"},
new Pulumi.Alias { Type = "azure-native:storage/v20190401:BlobContainer"},
new Pulumi.Alias { Type = "azure-nextgen:storage/v20190401:BlobContainer"},
new Pulumi.Alias { Type = "azure-native:storage/v20190601:BlobContainer"},
new Pulumi.Alias { Type = "azure-nextgen:storage/v20190601:BlobContainer"},
new Pulumi.Alias { Type = "azure-native:storage/v20200801preview:BlobContainer"},
new Pulumi.Alias { Type = "azure-nextgen:storage/v20200801preview:BlobContainer"},
new Pulumi.Alias { Type = "azure-native:storage/v20210101:BlobContainer"},
new Pulumi.Alias { Type = "azure-nextgen:storage/v20210101:BlobContainer"},
new Pulumi.Alias { Type = "azure-native:storage/v20210201:BlobContainer"},
new Pulumi.Alias { Type = "azure-nextgen:storage/v20210201:BlobContainer"},
new Pulumi.Alias { Type = "azure-native:storage/v20210401:BlobContainer"},
new Pulumi.Alias { Type = "azure-nextgen:storage/v20210401:BlobContainer"},
new Pulumi.Alias { Type = "azure-native:storage/v20210601:BlobContainer"},
new Pulumi.Alias { Type = "azure-nextgen:storage/v20210601:BlobContainer"},
},
};
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 BlobContainer 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 BlobContainer Get(string name, Input<string> id, CustomResourceOptions? options = null)
{
return new BlobContainer(name, id, options);
}
}
public sealed class BlobContainerArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The name of the storage account within the specified resource group. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only.
/// </summary>
[Input("accountName", required: true)]
public Input<string> AccountName { get; set; } = null!;
/// <summary>
/// The name of the blob container within the specified storage account. Blob container names must be between 3 and 63 characters in length and use numbers, lower-case letters and dash (-) only. Every dash (-) character must be immediately preceded and followed by a letter or number.
/// </summary>
[Input("containerName")]
public Input<string>? ContainerName { get; set; }
/// <summary>
/// Default the container to use specified encryption scope for all writes.
/// </summary>
[Input("defaultEncryptionScope")]
public Input<string>? DefaultEncryptionScope { get; set; }
/// <summary>
/// Block override of encryption scope from the container default.
/// </summary>
[Input("denyEncryptionScopeOverride")]
public Input<bool>? DenyEncryptionScopeOverride { get; set; }
[Input("metadata")]
private InputMap<string>? _metadata;
/// <summary>
/// A name-value pair to associate with the container as metadata.
/// </summary>
public InputMap<string> Metadata
{
get => _metadata ?? (_metadata = new InputMap<string>());
set => _metadata = value;
}
/// <summary>
/// Specifies whether data in the container may be accessed publicly and the level of access.
/// </summary>
[Input("publicAccess")]
public Input<Pulumi.AzureNative.Storage.PublicAccess>? PublicAccess { get; set; }
/// <summary>
/// The name of the resource group within the user's subscription. The name is case insensitive.
/// </summary>
[Input("resourceGroupName", required: true)]
public Input<string> ResourceGroupName { get; set; } = null!;
public BlobContainerArgs()
{
}
}
}
| 46.77821 | 302 | 0.613126 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/Storage/BlobContainer.cs | 12,022 | C# |
/**
* Copyright 2018 IBM Corp. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System.Collections.Generic;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace IBM.WatsonDeveloperCloud.Conversation.v1.Model
{
/// <summary>
/// CreateDialogNode.
/// </summary>
public class CreateDialogNode : BaseModel
{
/// <summary>
/// How the dialog node is processed.
/// </summary>
/// <value>
/// How the dialog node is processed.
/// </value>
[JsonConverter(typeof(StringEnumConverter))]
public enum NodeTypeEnum
{
/// <summary>
/// Enum STANDARD for standard
/// </summary>
[EnumMember(Value = "standard")]
STANDARD,
/// <summary>
/// Enum EVENT_HANDLER for event_handler
/// </summary>
[EnumMember(Value = "event_handler")]
EVENT_HANDLER,
/// <summary>
/// Enum FRAME for frame
/// </summary>
[EnumMember(Value = "frame")]
FRAME,
/// <summary>
/// Enum SLOT for slot
/// </summary>
[EnumMember(Value = "slot")]
SLOT,
/// <summary>
/// Enum RESPONSE_CONDITION for response_condition
/// </summary>
[EnumMember(Value = "response_condition")]
RESPONSE_CONDITION,
/// <summary>
/// Enum FOLDER for folder
/// </summary>
[EnumMember(Value = "folder")]
FOLDER
}
/// <summary>
/// How an `event_handler` node is processed.
/// </summary>
/// <value>
/// How an `event_handler` node is processed.
/// </value>
[JsonConverter(typeof(StringEnumConverter))]
public enum EventNameEnum
{
/// <summary>
/// Enum FOCUS for focus
/// </summary>
[EnumMember(Value = "focus")]
FOCUS,
/// <summary>
/// Enum INPUT for input
/// </summary>
[EnumMember(Value = "input")]
INPUT,
/// <summary>
/// Enum FILLED for filled
/// </summary>
[EnumMember(Value = "filled")]
FILLED,
/// <summary>
/// Enum VALIDATE for validate
/// </summary>
[EnumMember(Value = "validate")]
VALIDATE,
/// <summary>
/// Enum FILLED_MULTIPLE for filled_multiple
/// </summary>
[EnumMember(Value = "filled_multiple")]
FILLED_MULTIPLE,
/// <summary>
/// Enum GENERIC for generic
/// </summary>
[EnumMember(Value = "generic")]
GENERIC,
/// <summary>
/// Enum NOMATCH for nomatch
/// </summary>
[EnumMember(Value = "nomatch")]
NOMATCH,
/// <summary>
/// Enum NOMATCH_RESPONSES_DEPLETED for nomatch_responses_depleted
/// </summary>
[EnumMember(Value = "nomatch_responses_depleted")]
NOMATCH_RESPONSES_DEPLETED,
/// <summary>
/// Enum DIGRESSION_RETURN_PROMPT for digression_return_prompt
/// </summary>
[EnumMember(Value = "digression_return_prompt")]
DIGRESSION_RETURN_PROMPT
}
/// <summary>
/// Whether this top-level dialog node can be digressed into.
/// </summary>
/// <value>
/// Whether this top-level dialog node can be digressed into.
/// </value>
[JsonConverter(typeof(StringEnumConverter))]
public enum DigressInEnum
{
/// <summary>
/// Enum NOT_AVAILABLE for not_available
/// </summary>
[EnumMember(Value = "not_available")]
NOT_AVAILABLE,
/// <summary>
/// Enum RETURNS for returns
/// </summary>
[EnumMember(Value = "returns")]
RETURNS,
/// <summary>
/// Enum DOES_NOT_RETURN for does_not_return
/// </summary>
[EnumMember(Value = "does_not_return")]
DOES_NOT_RETURN
}
/// <summary>
/// Whether this dialog node can be returned to after a digression.
/// </summary>
/// <value>
/// Whether this dialog node can be returned to after a digression.
/// </value>
[JsonConverter(typeof(StringEnumConverter))]
public enum DigressOutEnum
{
/// <summary>
/// Enum ALLOW_RETURNING for allow_returning
/// </summary>
[EnumMember(Value = "allow_returning")]
ALLOW_RETURNING,
/// <summary>
/// Enum ALLOW_ALL for allow_all
/// </summary>
[EnumMember(Value = "allow_all")]
ALLOW_ALL,
/// <summary>
/// Enum ALLOW_ALL_NEVER_RETURN for allow_all_never_return
/// </summary>
[EnumMember(Value = "allow_all_never_return")]
ALLOW_ALL_NEVER_RETURN
}
/// <summary>
/// Whether the user can digress to top-level nodes while filling out slots.
/// </summary>
/// <value>
/// Whether the user can digress to top-level nodes while filling out slots.
/// </value>
[JsonConverter(typeof(StringEnumConverter))]
public enum DigressOutSlotsEnum
{
/// <summary>
/// Enum NOT_ALLOWED for not_allowed
/// </summary>
[EnumMember(Value = "not_allowed")]
NOT_ALLOWED,
/// <summary>
/// Enum ALLOW_RETURNING for allow_returning
/// </summary>
[EnumMember(Value = "allow_returning")]
ALLOW_RETURNING,
/// <summary>
/// Enum ALLOW_ALL for allow_all
/// </summary>
[EnumMember(Value = "allow_all")]
ALLOW_ALL
}
/// <summary>
/// How the dialog node is processed.
/// </summary>
[JsonProperty("type", NullValueHandling = NullValueHandling.Ignore)]
public NodeTypeEnum? NodeType { get; set; }
/// <summary>
/// How an `event_handler` node is processed.
/// </summary>
[JsonProperty("event_name", NullValueHandling = NullValueHandling.Ignore)]
public EventNameEnum? EventName { get; set; }
/// <summary>
/// Whether this top-level dialog node can be digressed into.
/// </summary>
[JsonProperty("digress_in", NullValueHandling = NullValueHandling.Ignore)]
public DigressInEnum? DigressIn { get; set; }
/// <summary>
/// Whether this dialog node can be returned to after a digression.
/// </summary>
[JsonProperty("digress_out", NullValueHandling = NullValueHandling.Ignore)]
public DigressOutEnum? DigressOut { get; set; }
/// <summary>
/// Whether the user can digress to top-level nodes while filling out slots.
/// </summary>
[JsonProperty("digress_out_slots", NullValueHandling = NullValueHandling.Ignore)]
public DigressOutSlotsEnum? DigressOutSlots { get; set; }
/// <summary>
/// The dialog node ID. This string must conform to the following restrictions:
/// - It can contain only Unicode alphanumeric, space, underscore, hyphen, and dot characters.
/// - It must be no longer than 1024 characters.
/// </summary>
[JsonProperty("dialog_node", NullValueHandling = NullValueHandling.Ignore)]
public string DialogNode { get; set; }
/// <summary>
/// The description of the dialog node. This string cannot contain carriage return, newline, or tab characters,
/// and it must be no longer than 128 characters.
/// </summary>
[JsonProperty("description", NullValueHandling = NullValueHandling.Ignore)]
public string Description { get; set; }
/// <summary>
/// The condition that will trigger the dialog node. This string cannot contain carriage return, newline, or tab
/// characters, and it must be no longer than 2048 characters.
/// </summary>
[JsonProperty("conditions", NullValueHandling = NullValueHandling.Ignore)]
public string Conditions { get; set; }
/// <summary>
/// The ID of the parent dialog node.
/// </summary>
[JsonProperty("parent", NullValueHandling = NullValueHandling.Ignore)]
public string Parent { get; set; }
/// <summary>
/// The ID of the previous dialog node.
/// </summary>
[JsonProperty("previous_sibling", NullValueHandling = NullValueHandling.Ignore)]
public string PreviousSibling { get; set; }
/// <summary>
/// The output of the dialog node. For more information about how to specify dialog node output, see the
/// [documentation](https://console.bluemix.net/docs/services/conversation/dialog-overview.html#complex).
/// </summary>
[JsonProperty("output", NullValueHandling = NullValueHandling.Ignore)]
public dynamic Output { get; set; }
/// <summary>
/// The context for the dialog node.
/// </summary>
[JsonProperty("context", NullValueHandling = NullValueHandling.Ignore)]
public object Context { get; set; }
/// <summary>
/// The metadata for the dialog node.
/// </summary>
[JsonProperty("metadata", NullValueHandling = NullValueHandling.Ignore)]
public object Metadata { get; set; }
/// <summary>
/// The next step to be executed in dialog processing.
/// </summary>
[JsonProperty("next_step", NullValueHandling = NullValueHandling.Ignore)]
public DialogNodeNextStep NextStep { get; set; }
/// <summary>
/// An array of objects describing any actions to be invoked by the dialog node.
/// </summary>
[JsonProperty("actions", NullValueHandling = NullValueHandling.Ignore)]
public List<DialogNodeAction> Actions { get; set; }
/// <summary>
/// The alias used to identify the dialog node. This string must conform to the following restrictions:
/// - It can contain only Unicode alphanumeric, space, underscore, hyphen, and dot characters.
/// - It must be no longer than 64 characters.
/// </summary>
[JsonProperty("title", NullValueHandling = NullValueHandling.Ignore)]
public string Title { get; set; }
/// <summary>
/// The location in the dialog context where output is stored.
/// </summary>
[JsonProperty("variable", NullValueHandling = NullValueHandling.Ignore)]
public string Variable { get; set; }
/// <summary>
/// A label that can be displayed externally to describe the purpose of the node to users. This string must be
/// no longer than 512 characters.
/// </summary>
[JsonProperty("user_label", NullValueHandling = NullValueHandling.Ignore)]
public string UserLabel { get; set; }
}
}
| 37.287879 | 120 | 0.550508 | [
"Apache-2.0"
] | anlblci/dotnetwatson | src/IBM.WatsonDeveloperCloud.Conversation.v1/Model/CreateDialogNode.cs | 12,305 | C# |
using System.Collections.Generic;
namespace rbkApiModules.UIAnnotations
{
public class FormDefinition
{
public FormDefinition(List<FormGroup> createInputs, List<FormGroup> updateInputs)
{
Create = createInputs;
Update = updateInputs;
}
public List<FormGroup> Create { get; }
public List<FormGroup> Update { get; }
}
}
| 23.352941 | 89 | 0.632242 | [
"MIT"
] | rbasniak/rbk-api-modules | rbkApiModules.UIAnnotations/Models/FormDefinition.cs | 399 | C# |
using System;
using System.Xml.Serialization;
using System.ComponentModel.DataAnnotations;
using BroadWorksConnector.Ocip.Validation;
using System.Collections.Generic;
namespace BroadWorksConnector.Ocip.Models
{
/// <summary>
/// Request to get a device profile file.
/// The response is either SystemAccessDeviceFileGetResponse or ErrorResponse.
/// Replaced By: SystemAccessDeviceFileGetRequest14sp8
/// <see cref="SystemAccessDeviceFileGetResponse"/>
/// <see cref="ErrorResponse"/>
/// <see cref="SystemAccessDeviceFileGetRequest14sp8"/>
/// </summary>
[Serializable]
[XmlRoot(Namespace = "")]
[Groups(@"[{""__type"":""Sequence:#BroadWorksConnector.Ocip.Validation"",""id"":""ab0042aa512abc10edb3c55e4b416b0b:4025""}]")]
public class SystemAccessDeviceFileGetRequest : BroadWorksConnector.Ocip.Models.C.OCIRequest
{
private string _deviceName;
[XmlElement(ElementName = "deviceName", IsNullable = false, Namespace = "")]
[Group(@"ab0042aa512abc10edb3c55e4b416b0b:4025")]
[MinLength(1)]
[MaxLength(40)]
public string DeviceName
{
get => _deviceName;
set
{
DeviceNameSpecified = true;
_deviceName = value;
}
}
[XmlIgnore]
protected bool DeviceNameSpecified { get; set; }
private string _fileType;
[XmlElement(ElementName = "fileType", IsNullable = false, Namespace = "")]
[Group(@"ab0042aa512abc10edb3c55e4b416b0b:4025")]
[MinLength(1)]
[MaxLength(40)]
public string FileType
{
get => _fileType;
set
{
FileTypeSpecified = true;
_fileType = value;
}
}
[XmlIgnore]
protected bool FileTypeSpecified { get; set; }
}
}
| 29.703125 | 130 | 0.612835 | [
"MIT"
] | JTOne123/broadworks-connector-net | BroadworksConnector/Ocip/Models/SystemAccessDeviceFileGetRequest.cs | 1,901 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Allgemeine Informationen über eine Assembly werden über die folgenden
// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
// die einer Assembly zugeordnet sind.
[assembly: AssemblyTitle("Stoppuhr")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Stoppuhr")]
[assembly: AssemblyCopyright("Copyright © 2019")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar
// für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von
// COM aus zugreifen müssen, sollten Sie das ComVisible-Attribut für diesen Typ auf "True" festlegen.
[assembly: ComVisible(false)]
// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird
[assembly: Guid("60ab302f-5f22-4d61-9dfa-d194a30ec476")]
// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten:
//
// Hauptversion
// Nebenversion
// Buildnummer
// Revision
//
// Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern
// übernehmen, indem Sie "*" eingeben:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 40.216216 | 106 | 0.759409 | [
"MIT"
] | Jonas-BBW/Exercises | Testing/Stoppuhr/Stoppuhr/Properties/AssemblyInfo.cs | 1,505 | C# |
using System;
using System.CodeDom;
using System.IO;
using System.Text;
using System.Web.Services.Configuration;
using System.Web.Services.Description;
using System.Web.Services.Protocols;
using System.Xml.Serialization;
namespace Commanigy.Iquomi.SoapExtensions {
// The YMLAttribute allows a developer to specify that the YML SOAP
// extension run on a per-method basis. The disabled property
// turns reversing the XML on and off.
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class YMLAttribute : SoapExtensionAttribute {
int priority = 0;
bool disabled = false;
public YMLAttribute() : this(false) { }
public YMLAttribute(bool disabled) {
this.disabled = disabled;
}
public override Type ExtensionType {
get { return typeof(YMLExtension); }
}
public override int Priority {
get { return priority; }
set { priority = value; }
}
public bool Disabled {
get { return disabled; }
set { disabled = value; }
}
}
public class YMLExtension : SoapExtension {
bool disabled = false;
Stream oldStream;
Stream newStream;
public override object GetInitializer(LogicalMethodInfo methodInfo,
SoapExtensionAttribute attribute) {
YMLAttribute attr = attribute as YMLAttribute;
if (attr != null) return attr.Disabled;
return false;
}
public override object GetInitializer(Type serviceType) {
return false;
}
public override void Initialize(object initializer) {
if (initializer is Boolean) disabled = (bool)initializer;
}
public override Stream ChainStream(Stream stream) {
if (disabled) return base.ChainStream(stream);
oldStream = stream;
newStream = new MemoryStream();
return newStream;
}
public override void ProcessMessage(SoapMessage message) {
if (disabled) return;
switch (message.Stage) {
case SoapMessageStage.BeforeSerialize:
Encode(message);
break;
case SoapMessageStage.AfterSerialize:
newStream.Position = 0;
Reverse(newStream, oldStream);
break;
case SoapMessageStage.BeforeDeserialize:
Decode(message);
break;
case SoapMessageStage.AfterDeserialize:
break;
}
}
void Encode(SoapMessage message) {
message.ContentType = "text/yml";
}
void Decode(SoapMessage message) {
if (message.ContentType != "text/yml")
throw new Exception("invalid content type:" + message.ContentType);
Reverse(oldStream, newStream);
newStream.Position = 0;
message.ContentType = "text/xml";
}
void Reverse(Stream from, Stream to) {
TextReader reader = new StreamReader(from);
TextWriter writer = new StreamWriter(to);
string line;
while ((line = reader.ReadLine()) != null) {
StringBuilder builder = new StringBuilder();
for (int i = line.Length - 1; i >= 0; i--) {
builder.Append(line[i]);
}
writer.WriteLine(builder.ToString());
}
writer.Flush();
}
}
// The YMLReflector class is part of the YML SDFE; it is
// called during the service description generation process.
public class YMLReflector : SoapExtensionReflector {
public override void ReflectMethod() {
ProtocolReflector reflector = ReflectionContext;
YMLAttribute attr = (YMLAttribute)reflector.Method.GetCustomAttribute(
typeof(YMLAttribute));
// If the YMLAttribute has been applied to this Web service
// method, adds the XML defined in the YMLOperationBinding class.
if (attr != null) {
YMLOperationBinding yml = new YMLOperationBinding();
yml.Reverse = !(attr.Disabled);
reflector.OperationBinding.Extensions.Add(yml);
}
ExtraType xt = new ExtraType();
reflector.ServiceDescription.Types.Extensions.Add(xt);
}
}
// The YMLImporter class is part of the YML SDFE; it is called when
// a proxy class is generated for each Web service method the proxy
// class communicates with. The class checks whether the service
// description contains the XML that this SDFE adds to a service
// description. If it exists, then the YMLExtension is applied to the
// method in the proxy class.
public class YMLImporter : SoapExtensionImporter {
public override void ImportMethod(CodeAttributeDeclarationCollection
metadata) {
SoapProtocolImporter importer = ImportContext;
// Checks whether the XML specified in the YMLOperationBinding is in
// the service description.
YMLOperationBinding yml = (YMLOperationBinding)
importer.OperationBinding.Extensions.Find(
typeof(YMLOperationBinding));
if (yml != null) {
// Only applies the YMLAttribute to the method when the XML should
// be reversed.
if (yml.Reverse) {
CodeAttributeDeclaration attr = new CodeAttributeDeclaration(
typeof(YMLAttribute).FullName);
attr.Arguments.Add(new CodeAttributeArgument(new
CodePrimitiveExpression(true)));
metadata.Add(attr);
}
}
}
}
// The YMLOperationBinding class is part of the YML SDFE; it is the
// class that is serialized into XML and placed in the service
// description.
[XmlFormatExtension("action", YMLOperationBinding.YMLNamespace,
typeof(OperationBinding))]
[XmlFormatExtensionPrefix("yml", YMLOperationBinding.YMLNamespace)]
public class YMLOperationBinding : ServiceDescriptionFormatExtension {
private Boolean reverse;
public const string YMLNamespace = "http://www.contoso.com/yml";
[XmlElement("Reverse")]
public Boolean Reverse {
get { return reverse; }
set { reverse = value; }
}
}
[XmlFormatExtension("TheillTest", "http://www.w3.org/2001/XMLSchema", typeof(Types))]
public class ExtraType : ServiceDescriptionFormatExtension {
[XmlElement("MyExtraType")]
public Boolean MyExtraType {
get {
return true;
}
}
}
} | 31.663102 | 87 | 0.696166 | [
"MIT"
] | theill/iquomi | server/soapextensions/WsdlExtender.cs | 5,921 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace LanguageServer.Parameters.TextDocument
{
/// <summary>
/// For <c>textDocument/willSave</c>
/// </summary>
public class WillSaveTextDocumentParams
{
public TextDocumentIdentifier textDocument { get; set; }
public TextDocumentSaveReason reason { get; set; }
}
}
| 23.352941 | 65 | 0.65995 | [
"MIT"
] | matarillo/LanguageServerProtocol | LanguageServer/Parameters/TextDocument/WillSaveTextDocumentParams.cs | 399 | C# |
namespace System;
partial class Func
{
public static IFunc<T1, T2, TResult> From<T1, T2, TResult>(
Func<T1, T2, TResult> func)
=>
new FuncImpl<T1, T2, TResult>(
func ?? throw new ArgumentNullException(nameof(func)));
}
| 23.636364 | 67 | 0.607692 | [
"MIT"
] | pfpack/pfpack-core-func | src/core-func-ext-sync/Func.Extensions.Sync/Factory.From/From.02.cs | 260 | C# |
//
// The MIT License(MIT)
//
// Copyright(c) 2015 Hans Wolff
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
using System;
using System.Text;
using FidoU2f.Models;
using Moq;
using NUnit.Framework;
namespace FidoU2f.Tests
{
[TestFixture]
public class TestFidoUniversalTwoFactor
{
[Test]
public void StartRegistration()
{
var randomChallenge = Encoding.Default.GetBytes("random challenge");
var mockGenerateChallenge = new Mock<IGenerateFidoChallenge>();
mockGenerateChallenge.Setup(x => x.GenerateChallenge()).Returns(randomChallenge);
var fido = new FidoUniversalTwoFactor(mockGenerateChallenge.Object);
var startedRegistration = fido.StartRegistration(TestVectors.AppIdEnroll);
mockGenerateChallenge.Verify(x => x.GenerateChallenge(), Times.Once);
Assert.AreEqual(TestVectors.AppIdEnroll, startedRegistration.AppId.ToString());
Assert.AreEqual(randomChallenge, WebSafeBase64Converter.FromBase64String(startedRegistration.Challenge));
}
[Test]
public void FinishRegistration_JsonRegisterResponse_Works()
{
var challenge = WebSafeBase64Converter.FromBase64String(TestVectors.ServerChallengeRegisterBase64);
var mockGenerateChallenge = new Mock<IGenerateFidoChallenge>();
mockGenerateChallenge.Setup(x => x.GenerateChallenge()).Returns(challenge);
var fido = new FidoUniversalTwoFactor();
var startedRegistration = fido.StartRegistration(TestVectors.AppIdEnroll);
startedRegistration.Challenge = TestVectors.ServerChallengeRegisterBase64;
var registerResponse = GetValidRegisterResponse();
var registrationData = registerResponse.RegistrationData;
var jsonValue = registerResponse.ToJson();
var deviceRegistration = fido.FinishRegistration(startedRegistration, jsonValue, TestVectors.TrustedDomains);
Assert.IsNotNull(deviceRegistration);
Assert.AreEqual(deviceRegistration.Certificate.RawData, registrationData.AttestationCertificate.RawData);
Assert.AreEqual(deviceRegistration.KeyHandle, registrationData.KeyHandle);
}
[Test]
public void FinishRegistration_RegisterResponse_Works()
{
var fido = new FidoUniversalTwoFactor();
var startedRegistration = fido.StartRegistration(TestVectors.AppIdEnroll);
startedRegistration.Challenge = TestVectors.ServerChallengeRegisterBase64;
var registerResponse = GetValidRegisterResponse();
var registrationData = registerResponse.RegistrationData;
var deviceRegistration = fido.FinishRegistration(startedRegistration, registerResponse, TestVectors.TrustedDomains);
Assert.IsNotNull(deviceRegistration);
Assert.AreEqual(deviceRegistration.Certificate.RawData, registrationData.AttestationCertificate.RawData);
Assert.AreEqual(deviceRegistration.KeyHandle, registrationData.KeyHandle);
}
[Test]
public void FinishRegistration_IncorrectType_Throws()
{
var fido = new FidoUniversalTwoFactor();
var startedRegistration = fido.StartRegistration(TestVectors.AppIdEnroll);
var registerResponse = GetValidRegisterResponse();
registerResponse.ClientData.Type = "incorrect type";
Assert.Throws<InvalidOperationException>(() => fido.FinishRegistration(startedRegistration, registerResponse, TestVectors.TrustedDomains));
}
[Test]
public void FinishRegistration_IncorrectChallenge_Throws()
{
var fido = new FidoUniversalTwoFactor();
var startedRegistration = fido.StartRegistration(TestVectors.AppIdEnroll);
var registerResponse = GetValidRegisterResponse();
registerResponse.ClientData.Challenge =
WebSafeBase64Converter.ToBase64String(Encoding.Default.GetBytes("incorrect challenge"));
Assert.Throws<InvalidOperationException>(() => fido.FinishRegistration(startedRegistration, registerResponse, TestVectors.TrustedDomains));
}
[TestCase("http://not.trusted")]
[TestCase("http://example.com:81")]
[TestCase("http://www.example.com")]
[TestCase("https://example.com")]
public void FinishRegistration_UntrustedOrigin_Throws(string origin)
{
var fido = new FidoUniversalTwoFactor();
var startedRegistration = fido.StartRegistration(TestVectors.AppIdEnroll);
var registerResponse = GetValidRegisterResponse();
registerResponse.ClientData.Origin = origin;
Assert.Throws<InvalidOperationException>(() => fido.FinishRegistration(startedRegistration, registerResponse, TestVectors.TrustedDomains));
}
[Test]
public void StartAuthentication()
{
var randomChallenge = Encoding.Default.GetBytes("random challenge");
var mockGenerateChallenge = new Mock<IGenerateFidoChallenge>();
mockGenerateChallenge.Setup(x => x.GenerateChallenge()).Returns(randomChallenge);
var fido = new FidoUniversalTwoFactor(mockGenerateChallenge.Object);
var deviceRegistration = CreateTestDeviceRegistration();
var startedAuthentication = fido.StartAuthentication(new FidoAppId(TestVectors.AppIdEnroll), deviceRegistration);
mockGenerateChallenge.Verify(x => x.GenerateChallenge(), Times.Once);
Assert.AreEqual(TestVectors.AppIdEnroll, startedAuthentication.AppId.ToString());
Assert.AreEqual(randomChallenge, WebSafeBase64Converter.FromBase64String(startedAuthentication.Challenge));
Assert.AreEqual(deviceRegistration.KeyHandle, startedAuthentication.KeyHandle);
}
[Test]
public void FinishAuthentication_Works()
{
var mockGenerateChallenge = new Mock<IGenerateFidoChallenge>();
mockGenerateChallenge.Setup(x => x.GenerateChallenge()).Returns(WebSafeBase64Converter.FromBase64String(TestVectors.ServerChallengeAuthBase64));
var fido = new FidoUniversalTwoFactor(mockGenerateChallenge.Object);
var deviceRegistration = CreateTestDeviceRegistration();
var startedAuthentication = fido.StartAuthentication(new FidoAppId(TestVectors.AppIdEnroll), deviceRegistration);
var authenticateResponse = new FidoAuthenticateResponse(
FidoClientData.FromJson(TestVectors.ClientDataAuth),
FidoSignatureData.FromWebSafeBase64(TestVectors.SignResponseDataBase64),
FidoKeyHandle.FromWebSafeBase64(TestVectors.KeyHandle));
fido.FinishAuthentication(startedAuthentication, authenticateResponse, deviceRegistration, TestVectors.TrustedDomains);
}
[Test]
public void FinishAuthentication_DifferentChallenge()
{
var mockGenerateChallenge = new Mock<IGenerateFidoChallenge>();
mockGenerateChallenge.Setup(x => x.GenerateChallenge()).Returns(WebSafeBase64Converter.FromBase64String(TestVectors.ServerChallengeAuthBase64));
var fido = new FidoUniversalTwoFactor(mockGenerateChallenge.Object);
var deviceRegistration = CreateTestDeviceRegistration();
var startedAuthentication = fido.StartAuthentication(new FidoAppId(TestVectors.AppIdEnroll), deviceRegistration);
var clientDataAuth = TestVectors.ClientDataAuth.Replace("challenge\":\"opsXqUifDriAAmWclinfbS0e-USY0CgyJHe_Otd7z8o", "challenge\":\"different");
var authenticateResponse = new FidoAuthenticateResponse(
FidoClientData.FromJson(clientDataAuth),
FidoSignatureData.FromWebSafeBase64(TestVectors.SignResponseDataBase64),
FidoKeyHandle.FromWebSafeBase64(TestVectors.KeyHandle));
Assert.Throws<InvalidOperationException>(() => fido.FinishAuthentication(startedAuthentication, authenticateResponse, deviceRegistration, TestVectors.TrustedDomains));
}
[Test]
public void FinishAuthentication_DifferentType()
{
var mockGenerateChallenge = new Mock<IGenerateFidoChallenge>();
mockGenerateChallenge.Setup(x => x.GenerateChallenge()).Returns(WebSafeBase64Converter.FromBase64String(TestVectors.ServerChallengeAuthBase64));
var fido = new FidoUniversalTwoFactor(mockGenerateChallenge.Object);
var deviceRegistration = CreateTestDeviceRegistration();
var startedAuthentication = fido.StartAuthentication(new FidoAppId(TestVectors.AppIdEnroll), deviceRegistration);
var clientDataAuth = TestVectors.ClientDataAuth.Replace("typ\":\"navigator.id.getAssertion", "typ\":\"different");
var authenticateResponse = new FidoAuthenticateResponse(
FidoClientData.FromJson(clientDataAuth),
FidoSignatureData.FromWebSafeBase64(TestVectors.SignResponseDataBase64),
FidoKeyHandle.FromWebSafeBase64(TestVectors.KeyHandle));
Assert.Throws<InvalidOperationException>(() => fido.FinishAuthentication(startedAuthentication, authenticateResponse, deviceRegistration, TestVectors.TrustedDomains));
}
[TestCase("http://example.com/subpath")]
[TestCase("http://example.com:80")]
[TestCase("http://example.com:80/subpath")]
public void FinishAuthentication_TrustedOrigin(string origin)
{
var mockGenerateChallenge = new Mock<IGenerateFidoChallenge>();
mockGenerateChallenge.Setup(x => x.GenerateChallenge()).Returns(WebSafeBase64Converter.FromBase64String(TestVectors.ServerChallengeAuthBase64));
var fido = new FidoUniversalTwoFactor(mockGenerateChallenge.Object);
var deviceRegistration = CreateTestDeviceRegistration();
var startedAuthentication = fido.StartAuthentication(new FidoAppId(TestVectors.AppIdEnroll), deviceRegistration);
var clientDataAuth = TestVectors.ClientDataAuth.Replace("origin\":\"http://example.com", "origin\":\"" + origin);
var authenticateResponse = new FidoAuthenticateResponse(
FidoClientData.FromJson(clientDataAuth),
FidoSignatureData.FromWebSafeBase64(TestVectors.SignResponseDataBase64),
FidoKeyHandle.FromWebSafeBase64(TestVectors.KeyHandle));
fido.FinishAuthentication(startedAuthentication, authenticateResponse, deviceRegistration, TestVectors.TrustedDomains);
}
[TestCase("http://not.trusted")]
[TestCase("http://example.com:81")]
[TestCase("http://www.example.com")]
[TestCase("https://example.com")]
public void FinishAuthentication_UntrustedOrigin(string origin)
{
var mockGenerateChallenge = new Mock<IGenerateFidoChallenge>();
mockGenerateChallenge.Setup(x => x.GenerateChallenge()).Returns(WebSafeBase64Converter.FromBase64String(TestVectors.ServerChallengeAuthBase64));
var fido = new FidoUniversalTwoFactor(mockGenerateChallenge.Object);
var deviceRegistration = CreateTestDeviceRegistration();
var startedAuthentication = fido.StartAuthentication(new FidoAppId(TestVectors.AppIdEnroll), deviceRegistration);
var clientDataAuth = TestVectors.ClientDataAuth.Replace("origin\":\"http://example.com", "origin\":\"" + origin);
var authenticateResponse = new FidoAuthenticateResponse(
FidoClientData.FromJson(clientDataAuth),
FidoSignatureData.FromWebSafeBase64(TestVectors.SignResponseDataBase64),
FidoKeyHandle.FromWebSafeBase64(TestVectors.KeyHandle));
Assert.Throws<InvalidOperationException>(() => fido.FinishAuthentication(startedAuthentication, authenticateResponse, deviceRegistration, TestVectors.TrustedDomains));
}
[Test]
public void FinishAuthentication_CounterTooSmall()
{
var mockGenerateChallenge = new Mock<IGenerateFidoChallenge>();
mockGenerateChallenge.Setup(x => x.GenerateChallenge()).Returns(WebSafeBase64Converter.FromBase64String(TestVectors.ServerChallengeAuthBase64));
var fido = new FidoUniversalTwoFactor(mockGenerateChallenge.Object);
var deviceRegistration = CreateTestDeviceRegistration();
var startedAuthentication = fido.StartAuthentication(new FidoAppId(TestVectors.AppIdEnroll), deviceRegistration);
var signatureData = FidoSignatureData.FromWebSafeBase64(TestVectors.SignResponseDataBase64);
signatureData = new FidoSignatureData(
signatureData.UserPresence,
0,
signatureData.Signature);
var authenticateResponse = new FidoAuthenticateResponse(
FidoClientData.FromJson(TestVectors.ClientDataAuth),
signatureData,
FidoKeyHandle.FromWebSafeBase64(TestVectors.KeyHandle));
Assert.Throws<InvalidOperationException>(() => fido.FinishAuthentication(startedAuthentication, authenticateResponse, deviceRegistration, TestVectors.TrustedDomains));
}
[Test]
public void FinishAuthentication_UserPresenceNotSet()
{
var mockGenerateChallenge = new Mock<IGenerateFidoChallenge>();
mockGenerateChallenge.Setup(x => x.GenerateChallenge()).Returns(WebSafeBase64Converter.FromBase64String(TestVectors.ServerChallengeAuthBase64));
var fido = new FidoUniversalTwoFactor(mockGenerateChallenge.Object);
var deviceRegistration = CreateTestDeviceRegistration();
var startedAuthentication = fido.StartAuthentication(new FidoAppId(TestVectors.AppIdEnroll), deviceRegistration);
var signatureData = FidoSignatureData.FromWebSafeBase64(TestVectors.SignResponseDataBase64);
signatureData = new FidoSignatureData(
0,
signatureData.Counter,
signatureData.Signature);
var authenticateResponse = new FidoAuthenticateResponse(
FidoClientData.FromJson(TestVectors.ClientDataAuth),
signatureData,
FidoKeyHandle.FromWebSafeBase64(TestVectors.KeyHandle));
Assert.Throws<InvalidOperationException>(() => fido.FinishAuthentication(startedAuthentication, authenticateResponse, deviceRegistration, TestVectors.TrustedDomains));
}
[Test]
public void FinishAuthentication_InvalidSignatureData()
{
var mockGenerateChallenge = new Mock<IGenerateFidoChallenge>();
mockGenerateChallenge.Setup(x => x.GenerateChallenge()).Returns(WebSafeBase64Converter.FromBase64String(TestVectors.ServerChallengeAuthBase64));
var fido = new FidoUniversalTwoFactor(mockGenerateChallenge.Object);
var deviceRegistration = CreateTestDeviceRegistration();
var startedAuthentication = fido.StartAuthentication(new FidoAppId(TestVectors.AppIdEnroll), deviceRegistration);
var signatureData = FidoSignatureData.FromWebSafeBase64(TestVectors.SignResponseDataBase64);
var signatureBytes = signatureData.Signature.ToByteArray();
signatureBytes[0] ^= 0xFF;
signatureData = new FidoSignatureData(
signatureData.UserPresence,
signatureData.Counter,
new FidoSignature(signatureBytes));
var authenticateResponse = new FidoAuthenticateResponse(
FidoClientData.FromJson(TestVectors.ClientDataAuth),
signatureData,
FidoKeyHandle.FromWebSafeBase64(TestVectors.KeyHandle));
Assert.Throws<InvalidOperationException>(() => fido.FinishAuthentication(startedAuthentication, authenticateResponse, deviceRegistration, TestVectors.TrustedDomains));
}
private static FidoRegisterResponse GetValidRegisterResponse()
{
var registerResponse = new FidoRegisterResponse
{
RegistrationData = FidoRegistrationData.FromWebSafeBase64(TestVectors.RegistrationResponseDataBase64),
ClientData = FidoClientData.FromJson(TestVectors.ClientDataRegister)
};
return registerResponse;
}
private static FidoDeviceRegistration CreateTestDeviceRegistration()
{
var cert = FidoAttestationCertificate.FromWebSafeBase64(TestVectors.AttestationCertificate);
var keyHandle = FidoKeyHandle.FromWebSafeBase64(TestVectors.KeyHandle);
var publicKey = FidoPublicKey.FromWebSafeBase64(TestVectors.PublicKeyBase64);
return new FidoDeviceRegistration(keyHandle, publicKey, cert, 0);
}
}
}
| 45.019718 | 170 | 0.799962 | [
"MIT"
] | hanswolff/fido-u2f-net | FidoU2f.Tests/TestFidoUniversalTwoFactor.cs | 15,984 | C# |
namespace EnvironmentAssessment.Common.VimApi
{
public enum VirtualDeviceConfigSpecFileOperation
{
create,
destroy,
replace
}
}
| 13.7 | 49 | 0.788321 | [
"MIT"
] | octansIt/environmentassessment | EnvironmentAssessment.Wizard/Common/VimApi/V/VirtualDeviceConfigSpecFileOperation.cs | 137 | C# |
using Roadie.Dlna.Server.Metadata;
namespace Roadie.Dlna.Server.Comparers
{
internal class DateComparer : TitleComparer
{
public override string Description => "Sort by file date";
public override string Name => "date";
public override int Compare(IMediaItem x, IMediaItem y)
{
var xm = x as IMetaInfo;
var ym = y as IMetaInfo;
if (xm != null && ym != null)
{
var rv = xm.InfoDate.CompareTo(ym.InfoDate);
if (rv != 0)
{
return rv;
}
}
return base.Compare(x, y);
}
}
} | 26.115385 | 66 | 0.4919 | [
"MIT"
] | sphildreth/roadie | Roadie.Dlna/Server/Comparers/DateComparer.cs | 681 | C# |
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using ImGuiNET;
using T3.Core;
using T3.Core.Logging;
using T3.Gui.Styling;
using T3.Gui.Windows;
namespace T3.Gui.UiHelpers
{
/// <summary>
/// Renders the <see cref="ConsoleLogWindow"/>
/// </summary>
public class StatusErrorLine : ILogWriter
{
public StatusErrorLine()
{
Log.AddWriter(this);
}
public void Draw()
{
if (_logEntries.Count == 0)
{
ImGui.TextUnformatted("Log empty");
return;
}
var lastEntry = _logEntries[_logEntries.Count - 1];
var color = ConsoleLogWindow.GetColorForLogLevel(lastEntry.Level)
.Fade(MathUtils.RemapAndClamp((float)lastEntry.SecondsAgo, 0, 1.5f, 1, 0.4f));
ImGui.PushFont(Fonts.FontBold);
var logMessage = lastEntry.Message;
if (lastEntry.Level == LogEntry.EntryLevel.Error)
{
logMessage = ExtractMeaningfulMessage(logMessage);
}
var width = ImGui.CalcTextSize(logMessage);
var availableSpace = ImGui.GetWindowContentRegionWidth();
ImGui.SetCursorPosX(availableSpace - width.X);
ImGui.TextColored(color, logMessage);
if (ImGui.IsItemClicked())
{
_logEntries.Clear();
}
if (ImGui.IsItemHovered())
{
ImGui.BeginTooltip();
{
var lastEntryTime = double.PositiveInfinity;
foreach (var entry in _logEntries)
{
var timeSinceLastEntry = entry.SecondsSinceStart - lastEntryTime;
if(timeSinceLastEntry > 1)
ImGui.Spacing();
lastEntryTime = entry.SecondsSinceStart;
var entryLevel = entry.Level;
ImGui.SetCursorPosX(-2);
ImGui.Value("", (float)entry.SecondsSinceStart); // Print with ImGui to avoid allocation
ImGui.SameLine(80);
ImGui.TextColored(ConsoleLogWindow.GetColorForLogLevel(entryLevel), entry.Message);
}
}
ImGui.EndTooltip();
}
ImGui.PopFont();
}
public void Dispose()
{
}
public LogEntry.EntryLevel Filter { get; set; }
public void ProcessEntry(LogEntry entry)
{
if (_logEntries.Count > 20)
{
_logEntries.RemoveAt(0);
}
_logEntries.Add(entry);
}
private string ExtractMeaningfulMessage(string message)
{
var shaderErrorMatch = _shaderErrorPattern.Match(message);
if (!shaderErrorMatch.Success)
return message;
var shaderName = shaderErrorMatch.Groups[1].Value;
var lineNumber = shaderErrorMatch.Groups[2].Value;
var errorMessage = shaderErrorMatch.Groups[3].Value;
errorMessage = errorMessage.Split('\n').First();
return $"{errorMessage} >>>> {shaderName}:{lineNumber}";
}
/// <summary>
/// Matches errors like....
///
/// Failed to compile shader 'ComputeWobble': C:\Users\pixtur\coding\t3\Resources\compute-ColorGrade.hlsl(32,12-56): warning X3206: implicit truncation of vector type
/// </summary>
private static readonly Regex _shaderErrorPattern = new Regex(@"Failed to compile shader.*\\(.*)\.hlsl\((.*)\):(.*)");
private readonly List<LogEntry> _logEntries = new List<LogEntry>();
}
} | 33.491379 | 174 | 0.533848 | [
"MIT"
] | still-scene/t3 | T3/Gui/UiHelpers/StatusErrorLine.cs | 3,887 | C# |
using EPiServer.Find;
using System.Collections.Specialized;
namespace Foundation.Features.Locations
{
public interface IFilterBlock
{
string FilterTitle { get; set; }
string AllConditionText { get; set; }
ITypeSearch<LocationItemPage.LocationItemPage> AddFilter(ITypeSearch<LocationItemPage.LocationItemPage> query);
ITypeSearch<LocationItemPage.LocationItemPage> ApplyFilter(ITypeSearch<LocationItemPage.LocationItemPage> query, NameValueCollection filters);
}
} | 31.9375 | 150 | 0.76908 | [
"Apache-2.0"
] | Beerwulf/foundation-mvc-cms | src/Foundation/Features/Locations/IFilterBlock.cs | 511 | 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("FaceEmotionRecognition.Droid")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Rogerio Rodrigues")]
[assembly: AssemblyProduct("FaceEmotionRecognition.Droid")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[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)]
| 38.685714 | 85 | 0.743722 | [
"MIT"
] | rogeriorrodrigues/vssummit2017 | FaceEmotionRecognition/FaceEmotionRecognition/FaceEmotionRecognition.Droid/Properties/AssemblyInfo.cs | 1,357 | C# |
namespace Georadix.WebApi
{
using Georadix.WebApi.Testing;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics.CodeAnalysis;
using System.IdentityModel.Protocols.WSTrust;
using System.IdentityModel.Tokens;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Claims;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;
using Xunit;
public sealed class JwtValidationHandlerFixture : IDisposable
{
private readonly List<string> allowedAudiences = new List<string>(new string[] { "http://www.example.com" });
private readonly X509Certificate2 certificate;
private readonly string rootRoute;
private TestJwtValidationHandler jwtValidationHandler;
public JwtValidationHandlerFixture()
{
var store = new X509Store(StoreName.TrustedPeople);
store.Open(OpenFlags.ReadOnly);
var certName = ConfigurationManager.AppSettings["AuthCertName"];
this.certificate = store.Certificates.Cast<X509Certificate2>()
.Single(c => c.Subject.Equals(certName));
this.rootRoute = string.Format(
"{0}/entities", typeof(JwtValidationHandlerFixtureController).Name.ToLowerInvariant());
}
[Fact]
public async Task AccessingAnonymousResourceWithNoTokenReturnsOK()
{
using (var server = this.CreateServer())
{
var response = await server.Client.GetAsync(this.rootRoute);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
[Fact]
public async Task AccessingProtectedResourceWithNoTokenReturnsForbidden()
{
using (var server = this.CreateServer())
{
var response = await server.Client.PostAsJsonAsync<string>(this.rootRoute, "test");
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
}
}
[Fact]
public async Task AccessingProtectedResourceWithValidTokenReturnsIt()
{
using (var server = this.CreateServer())
{
server.Client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", this.GenerateAuthToken(this.allowedAudiences.First()));
var response = await server.Client.PostAsJsonAsync<string>(this.rootRoute, "test");
var content = await response.Content.ReadAsAsync<string>();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("test", content);
}
}
[Fact]
public void ConstructorWithNullTokenValidationParametersThrowsArgumentNullException()
{
var ex = Assert.Throws<ArgumentNullException>(
() => new JwtValidationHandler(null));
Assert.Equal("tokenValidationParameters", ex.ParamName);
}
public void Dispose()
{
if (this.jwtValidationHandler != null)
{
this.jwtValidationHandler.Dispose();
}
}
[Fact]
public async Task RequestWithMalformedTokenCallsOnValidateTokenException()
{
using (var server = this.CreateServer())
{
server.Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "dfggd");
var response = await server.Client.PostAsJsonAsync<string>(this.rootRoute, "test");
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
Assert.NotNull(this.jwtValidationHandler.TokenValidationException);
}
}
private InMemoryServer CreateServer(TokenValidationParameters tokenValidationParameters = null)
{
var server = new InMemoryServer();
tokenValidationParameters = tokenValidationParameters ?? new TokenValidationParameters()
{
AllowedAudiences = this.allowedAudiences,
SigningToken = new X509SecurityToken(this.certificate),
ValidIssuer = "self"
};
this.jwtValidationHandler = new TestJwtValidationHandler(tokenValidationParameters);
server.Configuration.MessageHandlers.Add(this.jwtValidationHandler);
server.Configuration.MapHttpAttributeRoutes();
return server;
}
private string GenerateAuthToken(string audience)
{
var now = DateTime.UtcNow;
var tokenHandler = new JwtSecurityTokenHandler();
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new Claim[]
{
new Claim(ClaimTypes.Name, "Username"),
new Claim(ClaimTypes.Role, "User"),
}),
TokenIssuerName = "self",
AppliesToAddress = audience,
Lifetime = new Lifetime(now, now.AddMinutes(2)),
SigningCredentials = new X509SigningCredentials(this.certificate)
};
SecurityToken token = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(token);
}
private class TestJwtValidationHandler : JwtValidationHandler
{
public TestJwtValidationHandler(TokenValidationParameters tokenValidationParameters)
: base(tokenValidationParameters)
{
}
public Exception TokenValidationException { get; private set; }
protected override void OnValidateTokenException(
HttpRequestMessage request, CancellationToken cancellationToken, Exception ex)
{
this.TokenValidationException = ex;
base.OnValidateTokenException(request, cancellationToken, ex);
}
}
}
[SuppressMessage("Microsoft.StyleCop.CSharp.MaintainabilityRules", "SA1402:FileMayOnlyContainASingleClass",
Justification = "Embedding this controller class inside the fixture causes routing to its methods to fail.")]
[RoutePrefix("jwtvalidationhandlerfixturecontroller/entities")]
public class JwtValidationHandlerFixtureController : ApiController
{
[AllowAnonymous]
[Route("")]
public string Get()
{
return "test";
}
[Authorize]
[Route("")]
public string Post([FromBody] string value)
{
return value;
}
}
} | 35.371134 | 117 | 0.618916 | [
"MIT"
] | Georadix/Georadix.NET | src/Georadix.WebApi.Tests/JwtValidationHandlerFixture.cs | 6,864 | C# |
using Loteria.Models;
using Loteria.Models.DTO;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Http;
namespace Loteria.api
{
public class SorteioController : ApiController
{
private LoteriaEntity entity = new LoteriaEntity();
private DbSet<Sorteio> MySorteio { get { return entity.Sorteio; } }
private LoteriaDAL dal = new LoteriaDAL();
// GET api/sorteio
public IHttpActionResult Get()
{
var sorteioDTOs = MySorteio.ToArray().Select(x => (SorteioDTO)x).ToArray();
return Ok(sorteioDTOs);
}
// GET api/sorteio/5
public IHttpActionResult Get(int id)
{
var sorteio = MySorteio.FirstOrDefault(p => p.Id == id);
if (sorteio != null)
{
return Ok((SorteioDTO)sorteio);
}
else
{
return NotFound();
}
}
// GET api/sorteio/corrent
[Route("api/sorteio/corrente/{idTipo}/{numSorteio}")]
[HttpGet]
public IHttpActionResult SorteioCorrente(int idTipo, int numSorteio)
{
var sorteio = MySorteio.FirstOrDefault(p => p.IdTipo == idTipo && p.NumSorteio == numSorteio);
if (sorteio != null)
{
return Ok((SorteioDTO)sorteio);
}
else
{
return NotFound();
}
}
// GET api/sorteio/portipo
[Route("api/sorteio/portipo/{idTipo}")]
[HttpGet]
public IHttpActionResult SorteiosPTipo(int idTipo)
{
var sorteios = MySorteio.Where(p => p.IdTipo == idTipo).ToArray();
var sorteioDTOs = sorteios.Select(x => (SorteioDTO)x).ToArray();
return Ok(sorteioDTOs);
}
// GET api/sorteio/corrent
[Route("api/sorteio/processa/{idSorteio}")]
[HttpGet]
public IHttpActionResult ProcessaSorteio(int idSorteio)
{
try
{
var sorteio = dal.ProcessaSorteio(idSorteio);
return Ok((SorteioDTO)sorteio);
}
catch (Exception ex)
{
var msg = ex.Message;
return BadRequest(msg);
}
}
// POST api/sorteio
public IHttpActionResult Post([FromBody]SorteioDTO sorteioDTO)
{
try
{
var idTipo = sorteioDTO.IdTipo;
var newSorteio = dal.CriaSorteio(idTipo);
return Ok((SorteioDTO)newSorteio);
}
catch (Exception ex)
{
var msg = ex.Message;
return BadRequest(msg);
}
}
// PUT api/sorteio/5
public IHttpActionResult Put(int id, [FromBody]SorteioDTO sorteioDTO)
{
try
{
var idSorteio = sorteioDTO.Id.Value;
var sorteioAutomaticao = sorteioDTO.SorteioAutomatico;
var numeros = sorteioDTO.Numeros;
var newSorteio = sorteioAutomaticao ? dal.FechaSorteio(idSorteio) : dal.FechaSorteio(idSorteio, numeros);
return Ok((SorteioDTO)newSorteio);
}
catch (Exception ex)
{
var msg = ex.Message;
return BadRequest(msg);
}
}
}
} | 29.728814 | 121 | 0.519669 | [
"MIT"
] | alemosbarbosa/Loteria | Loteria/api/SorteioController.cs | 3,510 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using LeakBlocker.Libraries.Common;
using LeakBlocker.Libraries.Common.Entities.Security;
namespace LeakBlocker.Agent.Core.Settings.Implementations
{
internal static class OrganizationalUnitHelper
{
public static bool IsInOrganizationalUnit(OrganizationalUnit ou, BaseUserAccount account)
{
return IsAccountInOrganizationalUnit(ou, account);
}
public static bool IsInOrganizationalUnit(OrganizationalUnit ou, BaseComputerAccount account)
{
return IsAccountInOrganizationalUnit(ou, account);
}
private static bool IsAccountInOrganizationalUnit(OrganizationalUnit ou, Account account)
{
string canonicalName = account.CanonicalName + '/';
canonicalName = canonicalName.Replace("//", "/");
string ouPath = ou.CanonicalName + '/';
ouPath = ouPath.Replace("//", "/");
return canonicalName.StartsWith(ouPath, StringComparison.OrdinalIgnoreCase);
}
}
}
| 32.939394 | 101 | 0.686293 | [
"MIT"
] | imanushin/leak-blocker | Projects/LeakBlocker.Agent.Core/Settings/Implementations/OrganizationalUnitHelper.cs | 1,089 | C# |
using System;
using System.Linq.Expressions;
namespace CalculatorLibrary
{
public static class Operations<T> where T : struct
{
public static T Add(T a, T b)
{
var paramA = Expression.Parameter(typeof(T), "a");
var paramB = Expression.Parameter(typeof(T), "b");
var body = Expression.Add(paramA, paramB);
var add = Expression.Lambda<Func<T, T, T>>(body, paramA, paramB).Compile();
return add(a, b);
}
public static T Subtract(T a, T b)
{
var paramA = Expression.Parameter(typeof(T), "a");
var paramB = Expression.Parameter(typeof(T), "b");
var body = Expression.Subtract(paramA, paramB);
var add = Expression.Lambda<Func<T, T, T>>(body, paramA, paramB).Compile();
return add(a, b);
}
public static T Multiply(T a, T b)
{
var paramA = Expression.Parameter(typeof(T), "a");
var paramB = Expression.Parameter(typeof(T), "b");
var body = Expression.Multiply(paramA, paramB);
var add = Expression.Lambda<Func<T, T, T>>(body, paramA, paramB).Compile();
return add(a, b);
}
public static T Divide(T a, T b)
{
var paramA = Expression.Parameter(typeof(T), "a");
var paramB = Expression.Parameter(typeof(T), "b");
var body = Expression.Divide(paramA, paramB);
var add = Expression.Lambda<Func<T, T, T>>(body, paramA, paramB).Compile();
return add(a, b);
}
}
}
| 28.333333 | 87 | 0.543034 | [
"MPL-2.0"
] | andreshetniak/Clout-It-C-19-04 | Students/OleksiiL/Calculator/CalculatorLibrary/Operations.cs | 1,617 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace Codes.Linus.IntVectors.Collections
{
[Serializable]
public sealed class DataMatrix2<T> : IDataMatrix2<T>
{
private List<T> rawData;
public DataMatrix2 ()
{
rawData = new List<T> ();
}
public DataMatrix2 (Vector2i size, T padding = default(T))
{
rawData = new List<T> ();
Resize (size, padding);
}
public int Count
{
get { return Size.x * Size.y; }
}
public Vector2i Size
{
get;
private set;
}
public bool IsReadOnly
{
get { return false; }
}
public T this [int x, int y]
{
get { return rawData [PositionToIndex(new Vector2i(x,y))]; }
set { rawData [PositionToIndex(new Vector2i(x,y))] = value; }
}
public T this [Vector2i index]
{
get { return this [index.x, index.y]; }
set { this [index.x, index.y] = value; }
}
public void Resize (Vector2i newSize, T padding = default(T))
{
this.Size = newSize;
Resize (rawData, Size.x * Size.y, padding);
}
IEnumerator IEnumerable.GetEnumerator ()
{
return rawData.GetEnumerator ();
}
public IEnumerator<T> GetEnumerator ()
{
return rawData.GetEnumerator ();
}
public void Clear()
{
this.rawData.Clear ();
Resize (Vector2i.zero);
}
public bool Contains (T item)
{
return rawData.Contains (item);
}
public Vector2i IndexToPosition (int index)
{
return new Vector2i (
index % Size.x,
(index / Size.x) % Size.y
);
}
public int PositionToIndex (Vector2i position)
{
return position.x +
position.y * Size.x;
}
private static void Resize (List<T> list, int size, T padding = default (T))
{
if (list.Count > size)
{
list.RemoveRange (size, list.Count - size);
} else
{
if (list.Capacity > size)
{
list.Capacity = size;
}
list.AddRange (Enumerable.Repeat (padding, size - list.Count));
}
}
}
}
| 17.963964 | 79 | 0.611334 | [
"MIT"
] | LinusVanElswijk/Unity-Int-Vectors | Codes/Linus/IntVectors/Collections/DataMatrix2.cs | 1,994 | C# |
using CognitiveMinion.Api.Hubs;
using CognitiveMinion.Api.Services;
using CognitiveMinion.LanguageUnderstanding.LuisAI;
using Elastic.Apm.AspNetCore;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Polly;
using System;
namespace CognitiveMinion.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 void ConfigureServices(IServiceCollection services)
{
services.AddOptions<LuisAiSettings>("LuisAI");
services.AddControllers();
services.AddHttpClient<IIdentityServerClient, IdentityServerClient>(client =>
{
client.BaseAddress = new Uri(Configuration["SSOAuthorityUrl"]);
client.DefaultRequestHeaders.Add("Accept", "application/json");
}).AddTransientHttpErrorPolicy(builder => builder.WaitAndRetryAsync(new[]
{
TimeSpan.FromSeconds(1),
TimeSpan.FromSeconds(2),
TimeSpan.FromSeconds(3)
}));
services.AddMemoryCache();
services.AddTransient<ProtectedApiBearerTokenHandler>();
services.AddHttpClient("LuisAI", client => { /*client.BaseAddress = new Uri(Configuration["LuisAIUrl"]);*/ });
services.AddHttpClient("JsnLogger");
services.AddSignalR();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseElasticApm(Configuration);
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapHub<ProcessingHub>("/processing");
});
}
}
}
| 32.736111 | 122 | 0.636402 | [
"MIT"
] | ops-ai/cognitive-minion | CognitiveMinion.Api/Startup.cs | 2,359 | C# |
using CondominioSmart.DataBase;
using CondominioSmart.Models;
using CondominioSmart.Services;
using CondominioSmart.Views.PopUps;
using Rg.Plugins.Popup.Services;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace CondominioSmart.ViewModels
{
public class ReclamacaoTabbedViewModel : BaseViewModel
{
#region Propriedade
private int _contador = 0;
public int Contador
{
get { return _contador; }
set { SetProperty(ref _contador, value); }
}
private readonly RealmRepository<Reclamacao> _realmRepository;
private readonly ReclamacaoRepository _reclamacaoRepository;
#endregion
#region Commands
#endregion
#region Construtor
public ReclamacaoTabbedViewModel()
{
// _realmRepository = new RealmRepository<Reclamacao>();
_reclamacaoRepository = new ReclamacaoRepository();
MudarContador();
Init();
}
#endregion
#region Métodos
private void MudarContador()
{
MessagingCenter.Subscribe<Reclamacao>(this, "Confirmacao", message =>
{
Init();
});
}
private void Init()
{
try
{
Contador = _reclamacaoRepository.GetAll().Count;
}
catch (Exception Ex)
{
App.Current.MainPage.DisplayAlert("", Ex.Message, "ok");
}
}
#endregion
}
}
| 22.971831 | 81 | 0.581852 | [
"MIT"
] | WillBrigida/Projeto-Smart-Condom-nio | CondominioSmart/CondominioSmart/ViewModels/ReclamacaoTabbedViewModel.cs | 1,634 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Datadog.Inputs
{
public sealed class DashboardWidgetGroupDefinitionArgs : Pulumi.ResourceArgs
{
[Input("backgroundColor")]
public Input<string>? BackgroundColor { get; set; }
[Input("bannerImg")]
public Input<string>? BannerImg { get; set; }
/// <summary>
/// The layout type of the dashboard. Valid values are `ordered`, `free`.
/// </summary>
[Input("layoutType", required: true)]
public Input<string> LayoutType { get; set; } = null!;
[Input("showTitle")]
public Input<bool>? ShowTitle { get; set; }
/// <summary>
/// The title of the dashboard.
/// </summary>
[Input("title")]
public Input<string>? Title { get; set; }
[Input("widgets", required: true)]
private InputList<Inputs.DashboardWidgetGroupDefinitionWidgetArgs>? _widgets;
/// <summary>
/// The list of widgets to display on the dashboard.
/// </summary>
public InputList<Inputs.DashboardWidgetGroupDefinitionWidgetArgs> Widgets
{
get => _widgets ?? (_widgets = new InputList<Inputs.DashboardWidgetGroupDefinitionWidgetArgs>());
set => _widgets = value;
}
public DashboardWidgetGroupDefinitionArgs()
{
}
}
}
| 31.377358 | 109 | 0.621768 | [
"ECL-2.0",
"Apache-2.0"
] | pulumi/pulumi-datadog | sdk/dotnet/Inputs/DashboardWidgetGroupDefinitionArgs.cs | 1,663 | C# |
//-----------------------------------------------------------------------
// <copyright file="ObjectController.cs" company="Google LLC">
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
//-----------------------------------------------------------------------
using System.Collections;
using UnityEngine;
/// <summary>
/// Controls target objects behaviour.
/// </summary>
public class ObjectController : MonoBehaviour
{
/// <summary>
/// The material to use when this object is inactive (not being gazed at).
/// </summary>
public Material InactiveMaterial;
/// <summary>
/// The material to use when this object is active (gazed at).
/// </summary>
public Material GazedAtMaterial;
// The objects are about 1 meter in radius, so the min/max target distance are
// set so that the objects are always within the room (which is about 5 meters
// across).
private const float _minObjectDistance = 2.5f;
private const float _maxObjectDistance = 3.5f;
private const float _minObjectHeight = 0.5f;
private const float _maxObjectHeight = 3.5f;
private Renderer _myRenderer;
private Vector3 _startingPosition;
/// <summary>
/// Start is called before the first frame update.
/// </summary>
public void Start()
{
_startingPosition = transform.parent.localPosition;
_myRenderer = GetComponent<Renderer>();
SetMaterial(false);
}
/// <summary>
/// Teleports this instance randomly when triggered by a pointer click.
/// </summary>
public void TeleportRandomly()
{
// Picks a random sibling, activates it and deactivates itself.
int sibIdx = transform.GetSiblingIndex();
int numSibs = transform.parent.childCount;
sibIdx = (sibIdx + Random.Range(1, numSibs)) % numSibs;
GameObject randomSib = transform.parent.GetChild(sibIdx).gameObject;
// Computes new object's location.
float angle = Random.Range(-Mathf.PI, Mathf.PI);
float distance = Random.Range(_minObjectDistance, _maxObjectDistance);
float height = Random.Range(_minObjectHeight, _maxObjectHeight);
Vector3 newPos = new Vector3(Mathf.Cos(angle) * distance, height,
Mathf.Sin(angle) * distance);
// Moves the parent to the new position (siblings relative distance from their parent is 0).
transform.parent.localPosition = newPos;
randomSib.SetActive(true);
gameObject.SetActive(false);
SetMaterial(false);
}
/// <summary>
/// This method is called by the Main Camera when it starts gazing at this GameObject.
/// </summary>
public void OnPointerEnter()
{
SetMaterial(true);
}
/// <summary>
/// This method is called by the Main Camera when it stops gazing at this GameObject.
/// </summary>
public void OnPointerExit()
{
SetMaterial(false);
}
/// <summary>
/// This method is called by the Main Camera when it is gazing at this GameObject and the screen
/// is touched.
/// </summary>
public void OnPointerClick()
{
TeleportRandomly();
}
/// <summary>
/// Sets this instance's material according to gazedAt status.
/// </summary>
///
/// <param name="gazedAt">
/// Value `true` if this object is being gazed at, `false` otherwise.
/// </param>
private void SetMaterial(bool gazedAt)
{
if (InactiveMaterial != null && GazedAtMaterial != null)
{
_myRenderer.material = gazedAt ? GazedAtMaterial : InactiveMaterial;
}
}
}
| 34.919355 | 101 | 0.614088 | [
"MIT"
] | le-incroyable1-dev/darknessVR | ObjectController.cs | 4,330 | C# |
/*
* DAWN OF LIGHT - The first free open source DAoC server emulator
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
*/
using System;
using System.IO;
using System.Reflection;
using DOL.GS;
using DOL.Database.Connection;
using NUnit.Framework;
namespace DOL.Server.Tests
{
/// <summary>
/// SetUpTests Start The Needed Environnement for Unit Tests
/// </summary>
[SetUpFixture]
public class SetUpTests
{
public SetUpTests()
{
}
/// <summary>
/// Create Game Server Instance for Tests
/// </summary>
public static void CreateGameServerInstance()
{
Console.WriteLine("Create Game Server Instance");
DirectoryInfo CodeBase = new FileInfo(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath).Directory;
Console.WriteLine("Code Base: " + CodeBase.FullName);
DirectoryInfo FakeRoot = CodeBase.Parent;
Console.WriteLine("Fake Root: " + FakeRoot.FullName);
if(GameServer.Instance == null)
{
GameServerConfiguration config = new GameServerConfiguration();
config.RootDirectory = FakeRoot.FullName;
config.DBType = ConnectionType.DATABASE_SQLITE;
config.DBConnectionString = string.Format("Data Source={0};Version=3;Pooling=False;Cache Size=1073741824;Journal Mode=Off;Synchronous=Off;Foreign Keys=True;Default Timeout=60",
Path.Combine(config.RootDirectory, "dol-tests-only.sqlite3.db"));
config.Port = 0; // Auto Choosing Listen Port
config.UDPPort = 0; // Auto Choosing Listen Port
config.IP = System.Net.IPAddress.Parse("127.0.0.1");
config.UDPIP = System.Net.IPAddress.Parse("127.0.0.1");
config.RegionIP = System.Net.IPAddress.Parse("127.0.0.1");
GameServer.CreateInstance(config);
Console.WriteLine("Game Server Instance Created !");
}
}
[SetUp]
public virtual void Init()
{
CreateGameServerInstance();
if (!GameServer.Instance.IsRunning)
{
Console.WriteLine("Starting GameServer");
if (!GameServer.Instance.Start())
{
Console.WriteLine("Error init GameServer");
}
}
else
{
Console.WriteLine("GameServer already running, skip init of Gameserver...");
}
}
[TearDown]
public void Dispose()
{
GameServer.Instance.Stop();
}
}
}
| 31.106383 | 180 | 0.701778 | [
"MIT"
] | blockchainhelppro/Wallet-For-Blackberry | SetUpTests.cs | 2,926 | C# |
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace BaGet.Core.Mirror
{
public interface IPackageDownloader
{
/// <summary>
/// Attempt to download a package.
/// </summary>
/// <param name="packageUri">The package to download.</param>
/// <param name="cancellationToken">The token to cancel the download.</param>
/// <returns>The package, or null if it couldn't be downloaded.</returns>
Task<Stream> DownloadOrNullAsync(Uri packageUri, CancellationToken cancellationToken);
}
}
| 31.157895 | 94 | 0.668919 | [
"MIT"
] | 3da/BaGet | src/BaGet.Core/Mirror/IPackageDownloader.cs | 594 | C# |
namespace P03.Telephony
{
public interface ICallable
{
string Call(string number);
}
}
| 13.5 | 35 | 0.62037 | [
"MIT"
] | VinsantSavov/SoftUni-Software-Engineering | CSharp-OOP/Homeworks-And-Labs/Interfaces and Abstraction/Exercise/Exercise/P03.Telephony/ICallable.cs | 110 | C# |
/*
* Authors:
* 钟峰(Popeye Zhong) <zongsoft@gmail.com>
*
* The MIT License (MIT)
*
* Copyright (C) 2015 Zongsoft Corporation <http://www.zongsoft.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Zongsoft.Regular
{
partial class AboutDialog
{
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
protected override void Dispose(bool disposing)
{
if(disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows 窗体设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要
/// 使用代码编辑器修改此方法的内容。
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(AboutDialog));
this.picBanner = new System.Windows.Forms.PictureBox();
this.lblProductName = new System.Windows.Forms.Label();
this.lblVersion = new System.Windows.Forms.Label();
this.lblCompanyName = new System.Windows.Forms.Label();
this.txtDescription = new System.Windows.Forms.TextBox();
this.btnOK = new System.Windows.Forms.Button();
this.txtCopyright = new System.Windows.Forms.TextBox();
((System.ComponentModel.ISupportInitialize)(this.picBanner)).BeginInit();
this.SuspendLayout();
//
// picBanner
//
this.picBanner.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)));
this.picBanner.Image = ((System.Drawing.Image)(resources.GetObject("picBanner.Image")));
this.picBanner.Location = new System.Drawing.Point(5, 4);
this.picBanner.Margin = new System.Windows.Forms.Padding(5, 4, 5, 4);
this.picBanner.Name = "picBanner";
this.picBanner.Size = new System.Drawing.Size(175, 353);
this.picBanner.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.picBanner.TabIndex = 26;
this.picBanner.TabStop = false;
//
// lblProductName
//
this.lblProductName.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.lblProductName.AutoEllipsis = true;
this.lblProductName.Location = new System.Drawing.Point(193, 7);
this.lblProductName.Margin = new System.Windows.Forms.Padding(8, 0, 5, 0);
this.lblProductName.MaximumSize = new System.Drawing.Size(0, 21);
this.lblProductName.Name = "lblProductName";
this.lblProductName.Size = new System.Drawing.Size(380, 21);
this.lblProductName.TabIndex = 27;
this.lblProductName.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// lblVersion
//
this.lblVersion.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.lblVersion.AutoEllipsis = true;
this.lblVersion.Location = new System.Drawing.Point(193, 28);
this.lblVersion.Margin = new System.Windows.Forms.Padding(8, 0, 5, 0);
this.lblVersion.MaximumSize = new System.Drawing.Size(0, 21);
this.lblVersion.Name = "lblVersion";
this.lblVersion.Size = new System.Drawing.Size(380, 21);
this.lblVersion.TabIndex = 25;
this.lblVersion.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// lblCompanyName
//
this.lblCompanyName.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.lblCompanyName.AutoEllipsis = true;
this.lblCompanyName.Location = new System.Drawing.Point(193, 58);
this.lblCompanyName.Margin = new System.Windows.Forms.Padding(8, 0, 5, 0);
this.lblCompanyName.MaximumSize = new System.Drawing.Size(0, 21);
this.lblCompanyName.Name = "lblCompanyName";
this.lblCompanyName.Size = new System.Drawing.Size(380, 21);
this.lblCompanyName.TabIndex = 29;
this.lblCompanyName.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// txtDescription
//
this.txtDescription.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.txtDescription.Location = new System.Drawing.Point(187, 160);
this.txtDescription.Margin = new System.Windows.Forms.Padding(8, 4, 5, 4);
this.txtDescription.Multiline = true;
this.txtDescription.Name = "txtDescription";
this.txtDescription.ReadOnly = true;
this.txtDescription.ScrollBars = System.Windows.Forms.ScrollBars.Both;
this.txtDescription.Size = new System.Drawing.Size(384, 162);
this.txtDescription.TabIndex = 30;
this.txtDescription.TabStop = false;
//
// btnOK
//
this.btnOK.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnOK.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.btnOK.Location = new System.Drawing.Point(493, 331);
this.btnOK.Margin = new System.Windows.Forms.Padding(5, 4, 5, 4);
this.btnOK.Name = "btnOK";
this.btnOK.Size = new System.Drawing.Size(80, 24);
this.btnOK.TabIndex = 31;
this.btnOK.Text = "确定(&O)";
//
// txtCopyright
//
this.txtCopyright.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.txtCopyright.Location = new System.Drawing.Point(193, 90);
this.txtCopyright.Multiline = true;
this.txtCopyright.Name = "txtCopyright";
this.txtCopyright.ReadOnly = true;
this.txtCopyright.Size = new System.Drawing.Size(377, 55);
this.txtCopyright.TabIndex = 32;
//
// AboutDialog
//
this.AcceptButton = this.btnOK;
this.CancelButton = this.btnOK;
this.ClientSize = new System.Drawing.Size(584, 362);
this.Controls.Add(this.txtCopyright);
this.Controls.Add(this.picBanner);
this.Controls.Add(this.lblProductName);
this.Controls.Add(this.lblVersion);
this.Controls.Add(this.lblCompanyName);
this.Controls.Add(this.txtDescription);
this.Controls.Add(this.btnOK);
this.Font = new System.Drawing.Font("Courier New", 10.02F);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.HelpButton = true;
this.Margin = new System.Windows.Forms.Padding(5, 4, 5, 4);
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "AboutDialog";
this.Padding = new System.Windows.Forms.Padding(11);
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "关于";
((System.ComponentModel.ISupportInitialize)(this.picBanner)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.PictureBox picBanner;
private System.Windows.Forms.Label lblProductName;
private System.Windows.Forms.Label lblVersion;
private System.Windows.Forms.Label lblCompanyName;
private System.Windows.Forms.TextBox txtDescription;
private System.Windows.Forms.Button btnOK;
private System.Windows.Forms.TextBox txtCopyright;
}
}
| 43.107143 | 154 | 0.727542 | [
"MIT"
] | Zongsoft/Zongsoft.Utilities.Regular | src/AboutDialog.Designer.cs | 8,581 | C# |
//
// Network.Device.cs
//
// Author:
// M.A. (https://github.com/mkahvi)
//
// Copyright (c) 2017-2018 M.A.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Net;
using System.Net.NetworkInformation;
namespace Taskmaster.Network
{
public class DeviceTraffic
{
public int Index;
public readonly TrafficData Delta;
public readonly TrafficData Total;
public DeviceTraffic()
{
Delta = new TrafficData();
Total = new TrafficData();
}
public DeviceTraffic(DeviceTraffic old)
{
Index = old.Index;
Delta = new TrafficData(old.Delta);
Total = new TrafficData(old.Total);
}
public DeviceTraffic(int index, TrafficData delta, TrafficData total)
{
Index = index;
Delta = delta;
Total = total;
}
}
public class DeviceTrafficEventArgs : EventArgs
{
public DeviceTraffic Traffic = new DeviceTraffic();
}
public class TrafficData
{
public long
/// <summary>
/// Unicast packets
/// </summary>
Unicast,
/// <summary>
/// Broadcast and Multicast packets
/// </summary>
NonUnicast,
Discards,
Errors,
Bytes,
/// <summary>
/// Unknown packets, only for incoming data.
/// </summary>
Unknown;
public void From(IPInterfaceStatistics stats, bool incoming = true)
{
if (incoming)
{
Unicast = stats.UnicastPacketsReceived;
NonUnicast = stats.NonUnicastPacketsReceived;
Discards = stats.IncomingPacketsDiscarded;
Errors = stats.IncomingPacketsWithErrors;
Unknown = stats.IncomingUnknownProtocolPackets;
Bytes = stats.BytesReceived;
}
else
{
Unicast = stats.UnicastPacketsSent;
NonUnicast = stats.NonUnicastPacketsSent;
Discards = stats.OutgoingPacketsDiscarded;
Errors = stats.OutgoingPacketsWithErrors;
Bytes = stats.BytesSent;
}
}
public TrafficData() { }
public TrafficData(TrafficData old)
{
Unicast = old.Unicast;
NonUnicast = old.NonUnicast;
Discards = old.Discards;
Errors = old.Errors;
Bytes = old.Bytes;
Unknown = old.Unknown;
}
}
public class Device
{
public int Index { get; set; }
public Guid Id { get; set; }
public string Name { get; set; } = string.Empty;
public NetworkInterfaceType Type { get; set; } = NetworkInterfaceType.Unknown;
public OperationalStatus Status { get; set; } = OperationalStatus.NotPresent;
public long Speed { get; set; }
public IPAddress? IPv4Address { get; set; }
public IPAddress? IPv6Address { get; set; }
public OperationalStatus IPv4Status { get; set; } = OperationalStatus.Unknown;
public OperationalStatus IPv6Status { get; set; } = OperationalStatus.Unknown;
// Stats
public TrafficData Outgoing { get; set; } = new TrafficData();
public TrafficData Incoming { get; set; } = new TrafficData();
}
} | 27.099291 | 80 | 0.70793 | [
"MIT"
] | enmoku/taskmaster | Network/Device.cs | 3,823 | C# |
using System;
using System.Collections;
using System.IO;
using System.Reflection;
namespace MapSerializer
{
public sealed class MapXmlSerializer : MapSerializerBase, IMapSerializer
{
public override void Serialize(TextWriter writer, object reference)
{
if (reference == null)
return;
var type = reference.GetType();
var typeName = IsNativeType(type) ? NormalizeName(type) : type.Name;
writer.Write($"<{typeName}>");
SerializeWithoutTypeName(writer, reference);
writer.Write($"</{typeName}>");
}
private static string NormalizeName(Type type)
{
if(IsNumeric(type))
{
return type.Name.ToLowerInvariant().Trim('1', '2', '3', '4', '6');
}
return type.Name.ToLowerInvariant();
}
private void SerializeWithoutTypeName(TextWriter writer, object reference)
{
var type = reference.GetType();
if (IsEnumerable(type))
SerializeEnumerable(writer, reference);
else if (IsMapped(type))
SerializeMappedType(writer, reference, this.MappedTypes[type]);
else
writer.Write(reference);
}
private bool IsMapped(Type type)
{
return this.MappedTypes.ContainsKey(type);
}
private void SerializeMappedType(TextWriter writer, object reference, TypeMapBase map)
{
foreach (var propMap in map.MappedProperties)
SerializeMappedProperty(writer, propMap.PropertyInfo, reference);
}
private void SerializeMappedProperty(TextWriter writer, PropertyInfo propertyInfo, object reference)
{
writer.Write($"<{propertyInfo.Name}>");
var value = propertyInfo.GetValue(reference);
if (value != null)
{
if (IsNativeType(propertyInfo.PropertyType))
{
if (IsDateTime(propertyInfo.PropertyType))
writer.Write(value.ToDateTimeString());
else
writer.Write(value);
}
else if (IsEnumerable(propertyInfo.PropertyType))
{
SerializeEnumerable(writer, value);
}
else
{
SerializeWithoutTypeName(writer, value);
}
}
writer.Write($"</{propertyInfo.Name}>");
}
private void SerializeEnumerable(TextWriter writer, object value)
{
var enumerable = value as IEnumerable;
foreach (var item in enumerable)
Serialize(writer, item);
}
}
}
| 31.244681 | 109 | 0.523664 | [
"MIT"
] | flaviokodama/MapSerializer | src/MapSerializer/MapXmlSerializer.cs | 2,939 | C# |
#if !NETSTANDARD13
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the redshift-2012-12-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Threading;
using System.Threading.Tasks;
using Amazon.Runtime;
namespace Amazon.Redshift.Model
{
/// <summary>
/// Base class for DescribeReservedNodeOfferings paginators.
/// </summary>
internal sealed partial class DescribeReservedNodeOfferingsPaginator : IPaginator<DescribeReservedNodeOfferingsResponse>, IDescribeReservedNodeOfferingsPaginator
{
private readonly IAmazonRedshift _client;
private readonly DescribeReservedNodeOfferingsRequest _request;
private int _isPaginatorInUse = 0;
/// <summary>
/// Enumerable containing all full responses for the operation
/// </summary>
public IPaginatedEnumerable<DescribeReservedNodeOfferingsResponse> Responses => new PaginatedResponse<DescribeReservedNodeOfferingsResponse>(this);
/// <summary>
/// Enumerable containing all of the ReservedNodeOfferings
/// </summary>
public IPaginatedEnumerable<ReservedNodeOffering> ReservedNodeOfferings =>
new PaginatedResultKeyResponse<DescribeReservedNodeOfferingsResponse, ReservedNodeOffering>(this, (i) => i.ReservedNodeOfferings);
internal DescribeReservedNodeOfferingsPaginator(IAmazonRedshift client, DescribeReservedNodeOfferingsRequest request)
{
this._client = client;
this._request = request;
}
#if BCL
IEnumerable<DescribeReservedNodeOfferingsResponse> IPaginator<DescribeReservedNodeOfferingsResponse>.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 marker = _request.Marker;
DescribeReservedNodeOfferingsResponse response;
do
{
_request.Marker = marker;
response = _client.DescribeReservedNodeOfferings(_request);
marker = response.Marker;
yield return response;
}
while (marker != null);
}
#endif
#if AWS_ASYNC_ENUMERABLES_API
async IAsyncEnumerable<DescribeReservedNodeOfferingsResponse> IPaginator<DescribeReservedNodeOfferingsResponse>.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 marker = _request.Marker;
DescribeReservedNodeOfferingsResponse response;
do
{
_request.Marker = marker;
response = await _client.DescribeReservedNodeOfferingsAsync(_request, cancellationToken).ConfigureAwait(false);
marker = response.Marker;
cancellationToken.ThrowIfCancellationRequested();
yield return response;
}
while (marker != null);
}
#endif
}
}
#endif | 41.113402 | 180 | 0.682297 | [
"Apache-2.0"
] | DetlefGolze/aws-sdk-net | sdk/src/Services/Redshift/Generated/Model/_bcl45+netstandard/DescribeReservedNodeOfferingsPaginator.cs | 3,988 | C# |
using System.Security.Claims;
using API.Abstractions.Helpers.Auth.Authenticators;
using API.Abstractions.Services;
using API.DTOs.Account;
using API.DTOs.Role;
using API.Helpers.Auth;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace API.Controllers.Account;
public class AccountController : BaseApiController
{
private readonly IUserService userService;
private readonly IAuthenticator authenticator;
#region Constructor
public AccountController(
IUserService userService,
IAuthenticator authenticator)
{
this.userService = userService;
this.authenticator = authenticator;
}
#endregion
[AllowAnonymous]
[HttpPost("login")]
public ActionResult Login([FromBody] LoginDto loginInfo)
{
if (!userService.IsValidUser(loginInfo.Email, loginInfo.Password, out var user))
return BadRequest("Invalid password!");
if (user is null)
return BadRequest("User not found!");
var tokenDto = authenticator.GenerateToken(user.Id, user.Email, user.Role.Name);
return Ok(new AccessDto
{
Id = user.Id,
Email = user.Email,
Role = new RoleDto
{
Id = user.Role.Id,
Name = user.Role.Name
},
AccessToken = tokenDto.AccessToken,
ExpiresIn = authenticator.AccessTokenExpirationMinutes * 60 * 1000,
RefreshToken = tokenDto.RefreshToken,
});
}
[Authorize]
[HttpPost("refresh")]
public async Task<IActionResult> Refresh([FromBody] RefreshDto refreshInfo)
{
if (!authenticator.ValidateRefreshToken(refreshInfo.RefreshToken))
return BadRequest("Invalid refresh token!");
var accessToken =
await HttpContext.GetTokenAsync(JwtBearerDefaults.AuthenticationScheme, "access_token");
var tokenDto = authenticator.RefreshToken(refreshInfo.RefreshToken, accessToken);
authenticator.AddTokenToBlackList(accessToken);
return Ok(tokenDto);
}
[Authorize]
[HttpDelete("logout")]
public async Task<ActionResult> Logout()
{
if (!Guid.TryParse(HttpContext.User.FindFirstValue(CustomClaimTypes.Id), out var userId))
return BadRequest("Invalid user id!");
authenticator.DeleteRefreshToken(userId);
var accessToken =
await HttpContext.GetTokenAsync(JwtBearerDefaults.AuthenticationScheme, "access_token");
authenticator.AddTokenToBlackList(accessToken);
return Ok();
}
}
| 29.521739 | 100 | 0.673785 | [
"MIT"
] | cdcd72/Net.JwtAuth.Demo | src/API/Controllers/Account/AccountController.cs | 2,716 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.DocAsCode.AzureMarkdownRewriters
{
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using Microsoft.DocAsCode.Dfm;
using Microsoft.DocAsCode.Common;
using Microsoft.DocAsCode.MarkdownLite;
public class AzureMigrationEngineBuilder : GfmEngineBuilder
{
private const string MarkdownExtension = ".md";
public AzureMigrationEngineBuilder(Options options) : base(options)
{
BuildRules();
CreateRewriters();
}
protected override void BuildRules()
{
base.BuildRules();
BuildBlockRules();
BuildInlineRules();
}
protected override void BuildBlockRules()
{
base.BuildBlockRules();
var blockRules = BlockRules.ToList();
var index = blockRules.FindLastIndex(s => s is MarkdownNewLineBlockRule);
if (index < 0)
{
throw new ArgumentException($"{nameof(MarkdownNewLineBlockRule)} should exist!");
}
blockRules.InsertRange(
index + 1,
new IMarkdownRule[]
{
new DfmYamlHeaderBlockRule(),
new AzureMigrationIncludeBlockRule(),
new AzureMigrationVideoBlockRule(),
new AzureNoteBlockRule(),
new AzureSelectorBlockRule()
});
index = blockRules.FindLastIndex(s => s is MarkdownHtmlBlockRule);
if (index < 1)
{
throw new ArgumentException($"{nameof(MarkdownHtmlBlockRule)} should exist and shouldn't be the first one rule!");
}
blockRules.Insert(index - 1, new AzureMigrationHtmlMetadataBlockRule());
var markdownBlockQuoteIndex = blockRules.FindIndex(item => item is MarkdownBlockquoteBlockRule);
blockRules[markdownBlockQuoteIndex] = new AzureBlockquoteBlockRule();
BlockRules = blockRules.ToImmutableList();
}
protected override void BuildInlineRules()
{
base.BuildInlineRules();
var inlineRules = InlineRules.ToList();
var index = inlineRules.FindLastIndex(s => s is MarkdownLinkInlineRule);
if (index < 0)
{
throw new ArgumentException($"{nameof(MarkdownLinkInlineRule)} should exist!");
}
inlineRules.Insert(index, new AzureMigrationIncludeInlineRule());
// Remove GfmUrlInlineRule from inline rules as rewriter can just regards it as plain text
index = inlineRules.FindLastIndex(s => s is GfmUrlInlineRule);
inlineRules.RemoveAt(index);
InlineRules = inlineRules.ToImmutableList();
}
public override IMarkdownEngine CreateEngine(object renderer)
{
var engine = (MarkdownEngine)base.CreateEngine(renderer);
engine.MaxExtractCount = 100;
return engine;
}
protected void CreateRewriters()
{
Rewriter = MarkdownTokenRewriterFactory.Composite(
MarkdownTokenRewriterFactory.FromLambda(
(IMarkdownRewriteEngine e, AzureNoteBlockToken t) => new DfmNoteBlockToken(t.Rule, t.Context, t.NoteType.Substring("AZURE.".Length), t.Content, t.SourceInfo)
),
MarkdownTokenRewriterFactory.FromLambda(
(IMarkdownRewriteEngine e, AzureBlockquoteBlockToken t) => new MarkdownBlockquoteBlockToken(t.Rule, t.Context, t.Tokens, t.SourceInfo)
),
MarkdownTokenRewriterFactory.FromLambda(
(IMarkdownRewriteEngine e, MarkdownLinkInlineToken t) => new MarkdownLinkInlineToken(t.Rule, t.Context, NormalizeAzureLink(t.Href, MarkdownExtension, t.Context, t.SourceInfo.Markdown, t.SourceInfo.LineNumber.ToString()), t.Title, t.Content, t.SourceInfo, t.LinkType, t.RefId)
),
MarkdownTokenRewriterFactory.FromLambda(
(IMarkdownRewriteEngine e, MarkdownImageInlineToken t) => new MarkdownImageInlineToken(t.Rule, t.Context, CheckNonMdRelativeFileHref(t.Href, t.Context, t.SourceInfo.Markdown, t.SourceInfo.LineNumber.ToString()), t.Title, t.Text, t.SourceInfo, t.LinkType, t.RefId)
),
MarkdownTokenRewriterFactory.FromLambda(
(IMarkdownRewriteEngine e, AzureSelectorBlockToken t) => new DfmSectionBlockToken(t.Rule, t.Context, GenerateAzureSelectorAttributes(t.SelectorType, t.SelectorConditions), t.SourceInfo)
),
MarkdownTokenRewriterFactory.FromLambda(
(IMarkdownRewriteEngine e, AzureHtmlMetadataBlockToken t) => new DfmYamlHeaderBlockToken(t.Rule, t.Context, GenerateYamlHeaderContent(t.Properties, t.Tags), t.SourceInfo)
),
MarkdownTokenRewriterFactory.FromLambda(
(IMarkdownRewriteEngine e, AzureMigrationIncludeBlockToken t) => new DfmIncludeBlockToken(t.Rule, t.Context, t.Src, t.Name, t.Title, t.SourceInfo)
),
MarkdownTokenRewriterFactory.FromLambda(
(IMarkdownRewriteEngine e, AzureMigrationIncludeInlineToken t) => new DfmIncludeInlineToken(t.Rule, t.Context, t.Src, t.Name, t.Title, t.SourceInfo)
),
MarkdownTokenRewriterFactory.FromLambda(
(IMarkdownRewriteEngine e, AzureVideoBlockToken t) => new DfmVideoBlockToken(t.Rule, t.Context, GenerateAzureVideoLink(t.Context, t.VideoId, t.SourceInfo.Markdown, t.SourceInfo.LineNumber.ToString()), t.SourceInfo)
)
);
}
private string NormalizeAzureLink(string href, string defaultExtension, IMarkdownContext context, string rawMarkdown, string line)
{
string link = href;
// link change to the href result after append default extension.
var result = AppendDefaultExtension(href, defaultExtension, context, rawMarkdown, line);
link = result.Href;
// link change if the azure link need to be resolved.
if (result.NeedContinue && result.NeedResolveAzureLink.HasValue && result.NeedResolveAzureLink == true)
{
link = GenerateAzureLinkHref(context, link, rawMarkdown, line);
}
return link;
}
/// <summary>
/// Append default extension to href by condition
/// </summary>
/// <param name="href">original href string</param>
/// <param name="defaultExtension">default extension to append</param>
/// <returns>Href with default extension appended</returns>
private AppendDefaultExtensionResult AppendDefaultExtension(string href, string defaultExtension, IMarkdownContext context, string rawMarkdown, string line)
{
// If the context doesn't have necessary info, return the original href
if (!context.Variables.ContainsKey("path"))
{
return new AppendDefaultExtensionResult(false, href, null);
}
var currentFilePath = (string)context.Variables["path"];
try
{
if (!PathUtility.IsRelativePath(href))
{
return new AppendDefaultExtensionResult(false, href, null);
}
}
catch (ArgumentException)
{
Logger.LogWarning($"Invalid reference {href} in file: {currentFilePath}. Raw: {rawMarkdown}", null, currentFilePath, line);
return new AppendDefaultExtensionResult(false, href, null);
}
var index = href.IndexOf('#');
if (index == -1)
{
href = href.TrimEnd('/');
var extension = Path.GetExtension(href);
// Regard all the relative path with no extension as markdown file that missing .md
if (string.IsNullOrEmpty(extension))
{
return new AppendDefaultExtensionResult(true, $"{href}{defaultExtension}", true);
}
else
{
bool isMarkdownFile = extension.Equals(MarkdownExtension, StringComparison.OrdinalIgnoreCase);
return new AppendDefaultExtensionResult(true, href, isMarkdownFile);
}
}
else if (index == 0)
{
return new AppendDefaultExtensionResult(true, href, false);
}
else
{
var hrefWithoutAnchor = href.Remove(index).TrimEnd('/');
var anchor = href.Substring(index);
var extension = Path.GetExtension(hrefWithoutAnchor);
if (string.IsNullOrEmpty(extension))
{
return new AppendDefaultExtensionResult(true, $"{hrefWithoutAnchor}{defaultExtension}{anchor}", true);
}
else
{
bool isMarkdownFile = extension.Equals(MarkdownExtension, StringComparison.OrdinalIgnoreCase);
return new AppendDefaultExtensionResult(true, $"{hrefWithoutAnchor}{anchor}", isMarkdownFile);
}
}
}
private string GenerateAzureSelectorAttributes(string selectorType, string selectorConditions)
{
StringBuilder sb = new StringBuilder();
if (string.Equals(selectorType, "AZURE.SELECTOR", StringComparison.OrdinalIgnoreCase))
{
sb.Append("class=\"op_single_selector\"");
}
else if (string.Equals(selectorType, "AZURE.SELECTOR-LIST", StringComparison.OrdinalIgnoreCase))
{
sb.Append("class=\"op_multi_selector\"");
if (!string.IsNullOrEmpty(selectorConditions))
{
var conditions = selectorConditions.Split('|').Select(c => c.Trim());
int i = 0;
foreach (var condition in conditions)
{
sb.Append($" title{++i}=\"{HttpUtility.HtmlEncode(condition)}\"");
}
}
}
return sb.ToString();
}
private string GenerateYamlHeaderContent(IReadOnlyDictionary<string, string> properties, IReadOnlyDictionary<string, string> tags)
{
var propertiesSw = new StringWriter();
YamlUtility.Serialize(propertiesSw, properties);
var tagsSw = new StringWriter();
YamlUtility.Serialize(tagsSw, tags);
return MarkdownEngine.Normalize(propertiesSw.ToString() + "\n" + tagsSw.ToString());
}
private string GenerateAzureLinkHref(IMarkdownContext context, string href, string rawMarkdown, string line)
{
if (string.IsNullOrEmpty(href))
{
return string.Empty;
}
StringBuffer content = StringBuffer.Empty;
// If the context doesn't have necessary info, return the original href
if (!context.Variables.ContainsKey("path") || !context.Variables.ContainsKey("azureMarkdownFileInfoMapping"))
{
return href;
}
// if the href is not relative path, return it. Add try catch to keep this method safe.
try
{
if (!PathUtility.IsRelativePath(href))
{
return href;
}
}
catch (ArgumentException)
{
Logger.LogWarning($"Invalid reference {href} in file: {(string)context.Variables["path"]}. Raw: {rawMarkdown}", null, (string)context.Variables["path"], line);
return href;
}
// deal with bookmark. Get file name and anchor
string hrefFileName = string.Empty;
string anchor = string.Empty;
var index = href.IndexOf('#');
if (index == -1)
{
hrefFileName = Path.GetFileName(href);
}
else if (index == 0)
{
return href;
}
else
{
hrefFileName = Path.GetFileName(href.Remove(index));
anchor = href.Substring(index);
}
// deal with different kinds of relative paths
var currentFilePath = (string)context.Variables["path"];
var azureMarkdownFileInfoMapping = (IReadOnlyDictionary<string, AzureFileInfo>)context.Variables["azureMarkdownFileInfoMapping"];
if (azureMarkdownFileInfoMapping == null || !azureMarkdownFileInfoMapping.ContainsKey(hrefFileName))
{
Logger.LogWarning($"Can't find markdown reference: {href}. Raw: {rawMarkdown}.", null, currentFilePath, line);
return href;
}
string azureHref = null;
var hrefFileInfo = azureMarkdownFileInfoMapping[hrefFileName];
azureHref = string.Format("{0}{1}", PathUtility.MakeRelativePath(Path.GetDirectoryName(currentFilePath), hrefFileInfo.FilePath), anchor);
return azureHref;
}
private string CheckNonMdRelativeFileHref(string nonMdHref, IMarkdownContext context, string rawMarkdown, string line)
{
// If the context doesn't have necessary info or nonMdHref is not a relative path, return the original href
if (!context.Variables.ContainsKey("path") || !PathUtility.IsRelativePath(nonMdHref))
{
return nonMdHref;
}
var currentFilePath = (string)context.Variables["path"];
var currentFolderPath = Path.GetDirectoryName(currentFilePath);
var nonMdExpectedPath = Path.Combine(currentFolderPath, nonMdHref);
if (!File.Exists(nonMdExpectedPath))
{
Logger.LogWarning($"Can't find resource reference: {nonMdHref}. Raw: {rawMarkdown}.", null, currentFilePath, line);
}
return nonMdHref;
}
private string GenerateAzureVideoLink(IMarkdownContext context, string azureVideoId, string rawMarkdown, string line)
{
object path;
if (!context.Variables.TryGetValue("path", out path))
{
Logger.LogWarning("Can't get current file path. Skip video token rewriter.");
return azureVideoId;
}
if (!context.Variables.ContainsKey("azureVideoInfoMapping"))
{
Logger.LogWarning($"Can't find the whole azure video info mapping. Raw: {rawMarkdown}", null, path.ToString(), line);
return azureVideoId;
}
var azureVideoInfoMapping = (IReadOnlyDictionary<string, AzureVideoInfo>)context.Variables["azureVideoInfoMapping"];
if (azureVideoInfoMapping == null || !azureVideoInfoMapping.ContainsKey(azureVideoId))
{
Logger.LogWarning($"Can't find video reference: {azureVideoId}. Raw: {rawMarkdown}", null, path.ToString(), line);
return azureVideoId;
}
var azureVideoInfo = azureVideoInfoMapping[azureVideoId];
return azureVideoInfo.Link;
}
}
internal class AppendDefaultExtensionResult
{
public AppendDefaultExtensionResult(bool needContinue, string href, bool? needResolveAzureLink)
{
NeedContinue = needContinue;
Href = href;
NeedResolveAzureLink = needResolveAzureLink;
}
/// <summary>
/// Indicate whether need to continue to do the following transform for the href
/// </summary>
public bool NeedContinue { get; }
/// <summary>
/// Href after processing append default extension method
/// </summary>
public string Href { get; }
/// <summary>
/// True if it is a markdown file. Otherwise false. Null when the NeedContinue is false.
/// </summary>
public bool? NeedResolveAzureLink { get; }
}
}
| 45.024064 | 303 | 0.585189 | [
"MIT"
] | 928PJY/docfx | src/Microsoft.DocAsCode.AzureMarkdownRewriters/AzureMigrationEngineBuilder.cs | 16,841 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace SUS.MvcFramework
{
public interface IServiceCollection
{
// .Add <IUserService, UserService>
void Add<TSource, IDestionation>();
object CreateInstance(Type type);
}
}
| 20.214286 | 44 | 0.681979 | [
"MIT"
] | martinsivanov/CSharp-Web-May-2021 | SUS/SUS.MvcFramework/IServiceCollection.cs | 285 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Security;
using Umbraco.Core;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Core.Security;
using Umbraco.Web.Models;
using Umbraco.Web.PublishedCache;
using Umbraco.Core.Cache;
using Umbraco.Core.Composing;
using Umbraco.Core.Models.PublishedContent;
using Umbraco.Core.Services;
using Umbraco.Web.Editors;
namespace Umbraco.Web.Security
{
/// <summary>
/// A helper class for handling Members
/// </summary>
public class MembershipHelper
{
private readonly MembershipProvider _membershipProvider;
private readonly RoleProvider _roleProvider;
private readonly IMemberService _memberService;
private readonly IMemberTypeService _memberTypeService;
private readonly IUserService _userService;
private readonly IPublicAccessService _publicAccessService;
private readonly AppCaches _appCaches;
private readonly ILogger _logger;
#region Constructors
public MembershipHelper
(
HttpContextBase httpContext,
IPublishedMemberCache memberCache,
MembershipProvider membershipProvider,
RoleProvider roleProvider,
IMemberService memberService,
IMemberTypeService memberTypeService,
IUserService userService,
IPublicAccessService publicAccessService,
AppCaches appCaches,
ILogger logger
)
{
HttpContext = httpContext;
MemberCache = memberCache;
_memberService = memberService;
_memberTypeService = memberTypeService;
_userService = userService;
_publicAccessService = publicAccessService;
_appCaches = appCaches;
_logger = logger;
_membershipProvider = membershipProvider ?? throw new ArgumentNullException(nameof(membershipProvider));
_roleProvider = roleProvider ?? throw new ArgumentNullException(nameof(roleProvider));
}
#endregion
protected HttpContextBase HttpContext { get; }
protected IPublishedMemberCache MemberCache { get; }
/// <summary>
/// Check if a document object is protected by the "Protect Pages" functionality in umbraco
/// </summary>
/// <param name="path">The full path of the document object to check</param>
/// <returns>True if the document object is protected</returns>
public virtual bool IsProtected(string path)
{
//this is a cached call
return _publicAccessService.IsProtected(path);
}
public virtual IDictionary<string, bool> IsProtected(IEnumerable<string> paths)
{
var result = new Dictionary<string, bool>();
foreach (var path in paths)
{
//this is a cached call
result[path] = _publicAccessService.IsProtected(path);
}
return result;
}
/// <summary>
/// Check if the current user has access to a document
/// </summary>
/// <param name="path">The full path of the document object to check</param>
/// <returns>True if the current user has access or if the current document isn't protected</returns>
public virtual bool MemberHasAccess(string path)
{
if (IsProtected(path))
{
return IsLoggedIn() && HasAccess(path, Roles.Provider);
}
return true;
}
/// <summary>
/// Checks if the current user has access to the paths
/// </summary>
/// <param name="paths"></param>
/// <returns></returns>
public virtual IDictionary<string, bool> MemberHasAccess(IEnumerable<string> paths)
{
var protectedPaths = IsProtected(paths);
var pathsWithProtection = protectedPaths.Where(x => x.Value).Select(x => x.Key);
var pathsWithAccess = HasAccess(pathsWithProtection, Roles.Provider);
var result = new Dictionary<string, bool>();
foreach(var path in paths)
{
pathsWithAccess.TryGetValue(path, out var hasAccess);
// if it's not found it's false anyways
result[path] = !pathsWithProtection.Contains(path) || hasAccess;
}
return result;
}
/// <summary>
/// This will check if the member has access to this path
/// </summary>
/// <param name="path"></param>
/// <param name="roleProvider"></param>
/// <returns></returns>
private bool HasAccess(string path, RoleProvider roleProvider)
{
return _publicAccessService.HasAccess(path, CurrentUserName, roleProvider.GetRolesForUser);
}
private IDictionary<string, bool> HasAccess(IEnumerable<string> paths, RoleProvider roleProvider)
{
// ensure we only lookup user roles once
string[] userRoles = null;
string[] getUserRoles(string username)
{
if (userRoles != null) return userRoles;
userRoles = roleProvider.GetRolesForUser(username).ToArray();
return userRoles;
}
var result = new Dictionary<string, bool>();
foreach (var path in paths)
{
result[path] = IsLoggedIn() && _publicAccessService.HasAccess(path, CurrentUserName, getUserRoles);
}
return result;
}
/// <summary>
/// Returns true if the current membership provider is the Umbraco built-in one.
/// </summary>
/// <returns></returns>
public bool IsUmbracoMembershipProviderActive()
{
var provider = _membershipProvider;
return provider.IsUmbracoMembershipProvider();
}
/// <summary>
/// Updates the currently logged in members profile
/// </summary>
/// <param name="model"></param>
/// <returns>
/// The updated MembershipUser object
/// </returns>
public virtual Attempt<MembershipUser> UpdateMemberProfile(ProfileModel model)
{
if (IsLoggedIn() == false)
{
throw new NotSupportedException("No member is currently logged in");
}
//get the current membership user
var provider = _membershipProvider;
var membershipUser = provider.GetCurrentUser();
//NOTE: This should never happen since they are logged in
if (membershipUser == null) throw new InvalidOperationException("Could not find member with username " + HttpContext.User.Identity.Name);
try
{
//check if the email needs to change
if (model.Email.InvariantEquals(membershipUser.Email) == false)
{
//Use the membership provider to change the email since that is configured to do the checks to check for unique emails if that is configured.
var requiresUpdating = UpdateMember(membershipUser, provider, model.Email);
membershipUser = requiresUpdating.Result;
}
}
catch (Exception ex)
{
//This will occur if an email already exists!
return Attempt<MembershipUser>.Fail(ex);
}
var member = GetCurrentPersistedMember();
//NOTE: If changing the username is a requirement, than that needs to be done via the IMember directly since MembershipProvider's natively do
// not support changing a username!
if (model.Name != null && member.Name != model.Name)
{
member.Name = model.Name;
}
var memberType = _memberTypeService.Get(member.ContentTypeId);
if (model.MemberProperties != null)
{
foreach (var property in model.MemberProperties
//ensure the property they are posting exists
.Where(p => memberType.PropertyTypeExists(p.Alias))
.Where(property => member.Properties.Contains(property.Alias))
//needs to be editable
.Where(p => memberType.MemberCanEditProperty(p.Alias)))
{
member.Properties[property.Alias].SetValue(property.Value);
}
}
_memberService.Save(member);
//reset the FormsAuth cookie since the username might have changed
FormsAuthentication.SetAuthCookie(member.Username, true);
return Attempt<MembershipUser>.Succeed(membershipUser);
}
/// <summary>
/// Registers a new member
/// </summary>
/// <param name="model"></param>
/// <param name="status"></param>
/// <param name="logMemberIn">
/// true to log the member in upon successful registration
/// </param>
/// <returns></returns>
public virtual MembershipUser RegisterMember(RegisterModel model, out MembershipCreateStatus status, bool logMemberIn = true)
{
model.Username = (model.UsernameIsEmail || model.Username == null) ? model.Email : model.Username;
MembershipUser membershipUser;
var provider = _membershipProvider;
//update their real name
if (provider.IsUmbracoMembershipProvider())
{
membershipUser = ((UmbracoMembershipProviderBase)provider).CreateUser(
model.MemberTypeAlias,
model.Username, model.Password, model.Email,
// TODO: Support q/a http://issues.umbraco.org/issue/U4-3213
null, null,
true, null, out status);
if (status != MembershipCreateStatus.Success) return null;
var member = _memberService.GetByUsername(membershipUser.UserName);
member.Name = model.Name;
if (model.MemberProperties != null)
{
foreach (var property in model.MemberProperties.Where(p => p.Value != null)
.Where(property => member.Properties.Contains(property.Alias)))
{
member.Properties[property.Alias].SetValue(property.Value);
}
}
_memberService.Save(member);
}
else
{
membershipUser = provider.CreateUser(model.Username, model.Password, model.Email,
// TODO: Support q/a http://issues.umbraco.org/issue/U4-3213
null, null,
true, null, out status);
if (status != MembershipCreateStatus.Success) return null;
}
if (logMemberIn)
{
//Set member online
provider.GetUser(model.Username, true);
//Log them in
FormsAuthentication.SetAuthCookie(membershipUser.UserName, model.CreatePersistentLoginCookie);
}
return membershipUser;
}
/// <summary>
/// A helper method to perform the validation and logging in of a member - this is simply wrapping standard membership provider and asp.net forms auth logic.
/// </summary>
/// <param name="username"></param>
/// <param name="password"></param>
/// <returns></returns>
public virtual bool Login(string username, string password)
{
var provider = _membershipProvider;
//Validate credentials
if (provider.ValidateUser(username, password) == false)
{
return false;
}
// Get the member, do not set to online - this is done implicitly as part of ValidateUser which is consistent with
// how the .NET framework SqlMembershipProvider works. Passing in true will just cause more unnecessary SQL queries/locks.
var member = provider.GetUser(username, false);
if (member == null)
{
//this should not happen
Current.Logger.Warn<MembershipHelper, string>("The member validated but then no member was returned with the username {Username}", username);
return false;
}
//Log them in
FormsAuthentication.SetAuthCookie(member.UserName, true);
return true;
}
/// <summary>
/// Logs out the current member
/// </summary>
public virtual void Logout()
{
FormsAuthentication.SignOut();
}
#region Querying for front-end
public virtual IPublishedContent GetByProviderKey(object key)
{
return MemberCache.GetByProviderKey(key);
}
public virtual IEnumerable<IPublishedContent> GetByProviderKeys(IEnumerable<object> keys)
{
return keys?.Select(GetByProviderKey).WhereNotNull() ?? Enumerable.Empty<IPublishedContent>();
}
public virtual IPublishedContent GetById(int memberId)
{
return MemberCache.GetById(memberId);
}
public virtual IEnumerable<IPublishedContent> GetByIds(IEnumerable<int> memberIds)
{
return memberIds?.Select(GetById).WhereNotNull() ?? Enumerable.Empty<IPublishedContent>();
}
public virtual IPublishedContent GetById(Guid memberId)
{
return GetByProviderKey(memberId);
}
public virtual IEnumerable<IPublishedContent> GetByIds(IEnumerable<Guid> memberIds)
{
return GetByProviderKeys(memberIds.OfType<object>());
}
public virtual IPublishedContent GetByUsername(string username)
{
return MemberCache.GetByUsername(username);
}
public virtual IPublishedContent GetByEmail(string email)
{
return MemberCache.GetByEmail(email);
}
public virtual IPublishedContent Get(Udi udi)
{
var guidUdi = udi as GuidUdi;
if (guidUdi == null) return null;
var umbracoType = Constants.UdiEntityType.ToUmbracoObjectType(udi.EntityType);
var entityService = Current.Services.EntityService;
switch (umbracoType)
{
case UmbracoObjectTypes.Member:
// TODO: need to implement Get(guid)!
var memberAttempt = entityService.GetId(guidUdi.Guid, umbracoType);
if (memberAttempt.Success)
return GetById(memberAttempt.Result);
break;
}
return null;
}
/// <summary>
/// Returns the currently logged in member as IPublishedContent
/// </summary>
/// <returns></returns>
public virtual IPublishedContent GetCurrentMember()
{
if (IsLoggedIn() == false)
{
return null;
}
var result = GetCurrentPersistedMember();
return result == null ? null : MemberCache.GetByMember(result);
}
/// <summary>
/// Returns the currently logged in member id, -1 if they are not logged in
/// </summary>
/// <returns></returns>
public int GetCurrentMemberId()
{
if (IsLoggedIn() == false)
{
return -1;
}
var result = GetCurrentMember();
return result?.Id ?? -1;
}
#endregion
#region Model Creation methods for member data editing on the front-end
/// <summary>
/// Creates a new profile model filled in with the current members details if they are logged in which allows for editing
/// profile properties
/// </summary>
/// <returns></returns>
public virtual ProfileModel GetCurrentMemberProfileModel()
{
if (IsLoggedIn() == false)
{
return null;
}
var provider = _membershipProvider;
if (provider.IsUmbracoMembershipProvider())
{
var membershipUser = provider.GetCurrentUserOnline();
var member = GetCurrentPersistedMember();
//this shouldn't happen but will if the member is deleted in the back office while the member is trying
// to use the front-end!
if (member == null)
{
//log them out since they've been removed
FormsAuthentication.SignOut();
return null;
}
var model = ProfileModel.CreateModel();
model.Name = member.Name;
model.MemberTypeAlias = member.ContentTypeAlias;
model.Email = membershipUser.Email;
model.UserName = membershipUser.UserName;
model.PasswordQuestion = membershipUser.PasswordQuestion;
model.Comment = membershipUser.Comment;
model.IsApproved = membershipUser.IsApproved;
model.IsLockedOut = membershipUser.IsLockedOut;
model.LastLockoutDate = membershipUser.LastLockoutDate;
model.CreationDate = membershipUser.CreationDate;
model.LastLoginDate = membershipUser.LastLoginDate;
model.LastActivityDate = membershipUser.LastActivityDate;
model.LastPasswordChangedDate = membershipUser.LastPasswordChangedDate;
var memberType = _memberTypeService.Get(member.ContentTypeId);
var builtIns = Constants.Conventions.Member.GetStandardPropertyTypeStubs().Select(x => x.Key).ToArray();
model.MemberProperties = GetMemberPropertiesViewModel(memberType, builtIns, member).ToList();
return model;
}
//we can try to look up an associated member by the provider user key
// TODO: Support this at some point!
throw new NotSupportedException("Currently a member profile cannot be edited unless using the built-in Umbraco membership providers");
}
/// <summary>
/// Creates a model to use for registering new members with custom member properties
/// </summary>
/// <param name="memberTypeAlias"></param>
/// <returns></returns>
public virtual RegisterModel CreateRegistrationModel(string memberTypeAlias = null)
{
var provider = _membershipProvider;
if (provider.IsUmbracoMembershipProvider())
{
memberTypeAlias = memberTypeAlias ?? Constants.Conventions.MemberTypes.DefaultAlias;
var memberType = _memberTypeService.Get(memberTypeAlias);
if (memberType == null)
throw new InvalidOperationException("Could not find a member type with alias " + memberTypeAlias);
var builtIns = Constants.Conventions.Member.GetStandardPropertyTypeStubs().Select(x => x.Key).ToArray();
var model = RegisterModel.CreateModel();
model.MemberTypeAlias = memberTypeAlias;
model.MemberProperties = GetMemberPropertiesViewModel(memberType, builtIns).ToList();
return model;
}
else
{
var model = RegisterModel.CreateModel();
model.MemberTypeAlias = string.Empty;
return model;
}
}
private IEnumerable<UmbracoProperty> GetMemberPropertiesViewModel(IMemberType memberType, IEnumerable<string> builtIns, IMember member = null)
{
var viewProperties = new List<UmbracoProperty>();
foreach (var prop in memberType.PropertyTypes
.Where(x => builtIns.Contains(x.Alias) == false && memberType.MemberCanEditProperty(x.Alias))
.OrderBy(p => p.SortOrder))
{
var value = string.Empty;
if (member != null)
{
var propValue = member.Properties[prop.Alias];
if (propValue != null && propValue.GetValue() != null)
{
value = propValue.GetValue().ToString();
}
}
var viewProperty = new UmbracoProperty
{
Alias = prop.Alias,
Name = prop.Name,
Value = value
};
// TODO: Perhaps one day we'll ship with our own EditorTempates but for now developers
// can just render their own.
////This is a rudimentary check to see what data template we should render
//// if developers want to change the template they can do so dynamically in their views or controllers
//// for a given property.
////These are the default built-in MVC template types: “Boolean”, “Decimal”, “EmailAddress”, “HiddenInput”, “HTML”, “Object”, “String”, “Text”, and “Url”
//// by default we'll render a text box since we've defined that metadata on the UmbracoProperty.Value property directly.
//if (prop.DataTypeId == new Guid(Constants.PropertyEditors.TrueFalse))
//{
// viewProperty.EditorTemplate = "UmbracoBoolean";
//}
//else
//{
// switch (prop.DataTypeDatabaseType)
// {
// case DataTypeDatabaseType.Integer:
// viewProperty.EditorTemplate = "Decimal";
// break;
// case DataTypeDatabaseType.Ntext:
// viewProperty.EditorTemplate = "Text";
// break;
// case DataTypeDatabaseType.Date:
// case DataTypeDatabaseType.Nvarchar:
// break;
// }
//}
viewProperties.Add(viewProperty);
}
return viewProperties;
}
#endregion
/// <summary>
/// Gets the current user's roles.
/// </summary>
/// <remarks>Roles are cached per user name, at request level.</remarks>
public IEnumerable<string> GetCurrentUserRoles()
=> GetUserRoles(CurrentUserName);
/// <summary>
/// Gets a user's roles.
/// </summary>
/// <remarks>Roles are cached per user name, at request level.</remarks>
public IEnumerable<string> GetUserRoles(string userName)
{
// optimize by caching per-request (v7 cached per PublishedRequest, in PublishedRouter)
var key = "Umbraco.Web.Security.MembershipHelper__Roles__" + userName;
return _appCaches.RequestCache.GetCacheItem(key, () => Roles.Provider.GetRolesForUser(userName));
}
/// <summary>
/// Returns the login status model of the currently logged in member.
/// </summary>
/// <returns></returns>
public virtual LoginStatusModel GetCurrentLoginStatus()
{
var model = LoginStatusModel.CreateModel();
if (IsLoggedIn() == false)
{
model.IsLoggedIn = false;
return model;
}
var provider = _membershipProvider;
if (provider.IsUmbracoMembershipProvider())
{
var member = GetCurrentPersistedMember();
//this shouldn't happen but will if the member is deleted in the back office while the member is trying
// to use the front-end!
if (member == null)
{
//log them out since they've been removed
FormsAuthentication.SignOut();
model.IsLoggedIn = false;
return model;
}
model.Name = member.Name;
model.Username = member.Username;
model.Email = member.Email;
}
else
{
var member = provider.GetCurrentUserOnline();
//this shouldn't happen but will if the member is deleted in the back office while the member is trying
// to use the front-end!
if (member == null)
{
//log them out since they've been removed
FormsAuthentication.SignOut();
model.IsLoggedIn = false;
return model;
}
model.Name = member.UserName;
model.Username = member.UserName;
model.Email = member.Email;
}
model.IsLoggedIn = true;
return model;
}
/// <summary>
/// Check if a member is logged in
/// </summary>
/// <returns></returns>
public bool IsLoggedIn()
{
return HttpContext.User != null && HttpContext.User.Identity.IsAuthenticated;
}
/// <summary>
/// Returns the currently logged in username
/// </summary>
public string CurrentUserName => HttpContext.User.Identity.Name;
/// <summary>
/// Returns true or false if the currently logged in member is authorized based on the parameters provided
/// </summary>
/// <param name="allowTypes"></param>
/// <param name="allowGroups"></param>
/// <param name="allowMembers"></param>
/// <returns></returns>
public virtual bool IsMemberAuthorized(
IEnumerable<string> allowTypes = null,
IEnumerable<string> allowGroups = null,
IEnumerable<int> allowMembers = null)
{
if (allowTypes == null)
allowTypes = Enumerable.Empty<string>();
if (allowGroups == null)
allowGroups = Enumerable.Empty<string>();
if (allowMembers == null)
allowMembers = Enumerable.Empty<int>();
// Allow by default
var allowAction = true;
if (IsLoggedIn() == false)
{
// If not logged on, not allowed
allowAction = false;
}
else
{
var provider = _membershipProvider;
string username;
if (provider.IsUmbracoMembershipProvider())
{
var member = GetCurrentPersistedMember();
// If a member could not be resolved from the provider, we are clearly not authorized and can break right here
if (member == null)
return false;
username = member.Username;
// If types defined, check member is of one of those types
var allowTypesList = allowTypes as IList<string> ?? allowTypes.ToList();
if (allowTypesList.Any(allowType => allowType != string.Empty))
{
// Allow only if member's type is in list
allowAction = allowTypesList.Select(x => x.ToLowerInvariant()).Contains(member.ContentType.Alias.ToLowerInvariant());
}
// If specific members defined, check member is of one of those
if (allowAction && allowMembers.Any())
{
// Allow only if member's Id is in the list
allowAction = allowMembers.Contains(member.Id);
}
}
else
{
var member = provider.GetCurrentUser();
// If a member could not be resolved from the provider, we are clearly not authorized and can break right here
if (member == null)
return false;
username = member.UserName;
}
// If groups defined, check member is of one of those groups
var allowGroupsList = allowGroups as IList<string> ?? allowGroups.ToList();
if (allowAction && allowGroupsList.Any(allowGroup => allowGroup != string.Empty))
{
// Allow only if member is assigned to a group in the list
var groups = _roleProvider.GetRolesForUser(username);
allowAction = allowGroupsList.Select(s => s.ToLowerInvariant()).Intersect(groups.Select(myGroup => myGroup.ToLowerInvariant())).Any();
}
}
return allowAction;
}
/// <summary>
/// Changes password for a member/user given the membership provider name and the password change model
/// </summary>
/// <param name="username"></param>
/// <param name="passwordModel"></param>
/// <param name="membershipProviderName"></param>
/// <returns></returns>
public virtual Attempt<PasswordChangedModel> ChangePassword(string username, ChangingPasswordModel passwordModel, string membershipProviderName)
{
var provider = Membership.Providers[membershipProviderName];
if (provider == null)
{
throw new InvalidOperationException("Could not find provider with name " + membershipProviderName);
}
return ChangePassword(username, passwordModel, provider);
}
/// <summary>
/// Changes password for a member/user given the membership provider and the password change model
/// </summary>
/// <param name="username"></param>
/// <param name="passwordModel"></param>
/// <param name="membershipProvider"></param>
/// <returns></returns>
public virtual Attempt<PasswordChangedModel> ChangePassword(string username, ChangingPasswordModel passwordModel, MembershipProvider membershipProvider)
{
var passwordChanger = new PasswordChanger(_logger, _userService, HttpContext);
return passwordChanger.ChangePasswordWithMembershipProvider(username, passwordModel, membershipProvider);
}
/// <summary>
/// Updates a membership user with all of it's writable properties
/// </summary>
/// <param name="member"></param>
/// <param name="provider"></param>
/// <param name="email"></param>
/// <param name="isApproved"></param>
/// <param name="lastLoginDate"></param>
/// <param name="lastActivityDate"></param>
/// <param name="comment"></param>
/// <returns>
/// Returns successful if the membership user required updating, otherwise returns failed if it didn't require updating.
/// </returns>
internal Attempt<MembershipUser> UpdateMember(MembershipUser member, MembershipProvider provider,
string email = null,
bool? isApproved = null,
DateTime? lastLoginDate = null,
DateTime? lastActivityDate = null,
string comment = null)
{
var update = false;
if (email != null)
{
if (member.Email != email) update = true;
member.Email = email;
}
if (isApproved.HasValue)
{
if (member.IsApproved != isApproved.Value) update = true;
member.IsApproved = isApproved.Value;
}
if (lastLoginDate.HasValue)
{
if (member.LastLoginDate != lastLoginDate.Value) update = true;
member.LastLoginDate = lastLoginDate.Value;
}
if (lastActivityDate.HasValue)
{
if (member.LastActivityDate != lastActivityDate.Value) update = true;
member.LastActivityDate = lastActivityDate.Value;
}
if (comment != null)
{
if (member.Comment != comment) update = true;
member.Comment = comment;
}
if (update == false)
return Attempt<MembershipUser>.Fail(member);
provider.UpdateUser(member);
return Attempt<MembershipUser>.Succeed(member);
}
/// <summary>
/// Returns the currently logged in IMember object - this should never be exposed to the front-end since it's returning a business logic entity!
/// </summary>
/// <returns></returns>
private IMember GetCurrentPersistedMember()
{
var provider = _membershipProvider;
if (provider.IsUmbracoMembershipProvider() == false)
{
throw new NotSupportedException("An IMember model can only be retrieved when using the built-in Umbraco membership providers");
}
var username = provider.GetCurrentUserName();
// The result of this is cached by the MemberRepository
var member = _memberService.GetByUsername(username);
return member;
}
}
}
| 40.062722 | 169 | 0.562077 | [
"MIT"
] | AaronSadlerUK/Umbraco-CMS | src/Umbraco.Web/Security/MembershipHelper.cs | 33,891 | C# |
using System;
using System.Collections.Generic;
using Zenject;
using NUnit.Framework;
using ModestTree;
using Assert=ModestTree.Assert;
namespace Zenject.Tests.Injection
{
[TestFixture]
public class TestPostInjectParameters : ZenjectUnitTestFixture
{
class Test0
{
}
class Test1
{
}
class Test2
{
}
class Test3
{
public bool HasInitialized;
public Test0 test0 = null;
[Inject]
public Test1 test1 = null;
[Inject]
public void Init(
Test0 test0,
[InjectOptional]
Test2 test2)
{
Assert.That(!HasInitialized);
Assert.IsNotNull(test1);
Assert.IsNull(test2);
Assert.IsNull(this.test0);
this.test0 = test0;
HasInitialized = true;
}
}
[Test]
public void Test()
{
Container.Bind<Test1>().AsSingle().NonLazy();
Container.Bind<Test3>().AsSingle().NonLazy();
Container.Bind<Test0>().AsSingle().NonLazy();
var test3 = Container.Resolve<Test3>();
Assert.That(test3.HasInitialized);
Assert.IsNotNull(test3.test0);
}
}
}
| 21.4375 | 66 | 0.502187 | [
"MIT"
] | AdJion/Zenject | UnityProject/Assets/Plugins/Zenject/OptionalExtras/UnitTests/Editor/Injection/TestPostInjectParameters.cs | 1,372 | 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.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace Microsoft.Win32.SafeHandles
{
public abstract partial class SafeNCryptHandle : Microsoft.Win32.SafeHandles.SafeHandleZeroOrMinusOneIsInvalid
{
protected SafeNCryptHandle() : base (default(bool)) { }
protected SafeNCryptHandle(System.IntPtr handle, System.Runtime.InteropServices.SafeHandle parentHandle) : base (default(bool)) { }
public override bool IsInvalid { get { throw null; } }
protected override bool ReleaseHandle() { throw null; }
protected abstract bool ReleaseNativeHandle();
}
public sealed partial class SafeNCryptKeyHandle : Microsoft.Win32.SafeHandles.SafeNCryptHandle
{
public SafeNCryptKeyHandle() { }
public SafeNCryptKeyHandle(System.IntPtr handle, System.Runtime.InteropServices.SafeHandle parentHandle) { }
protected override bool ReleaseNativeHandle() { throw null; }
}
public sealed partial class SafeNCryptProviderHandle : Microsoft.Win32.SafeHandles.SafeNCryptHandle
{
public SafeNCryptProviderHandle() { }
protected override bool ReleaseNativeHandle() { throw null; }
}
public sealed partial class SafeNCryptSecretHandle : Microsoft.Win32.SafeHandles.SafeNCryptHandle
{
public SafeNCryptSecretHandle() { }
protected override bool ReleaseNativeHandle() { throw null; }
}
}
namespace System.Security.Cryptography
{
public sealed partial class AesCng : System.Security.Cryptography.Aes
{
public AesCng() { }
public AesCng(string keyName) { }
public AesCng(string keyName, System.Security.Cryptography.CngProvider provider) { }
public AesCng(string keyName, System.Security.Cryptography.CngProvider provider, System.Security.Cryptography.CngKeyOpenOptions openOptions) { }
public override byte[] Key { get { throw null; } set { } }
public override int KeySize { get { throw null; } set { } }
public override System.Security.Cryptography.ICryptoTransform CreateDecryptor() { throw null; }
public override System.Security.Cryptography.ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[] rgbIV) { throw null; }
public override System.Security.Cryptography.ICryptoTransform CreateEncryptor() { throw null; }
public override System.Security.Cryptography.ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[] rgbIV) { throw null; }
protected override void Dispose(bool disposing) { }
public override void GenerateIV() { }
public override void GenerateKey() { }
}
public sealed partial class CngAlgorithm : System.IEquatable<System.Security.Cryptography.CngAlgorithm>
{
public CngAlgorithm(string algorithm) { }
public string Algorithm { get { throw null; } }
public static System.Security.Cryptography.CngAlgorithm ECDiffieHellman { get { throw null; } }
public static System.Security.Cryptography.CngAlgorithm ECDiffieHellmanP256 { get { throw null; } }
public static System.Security.Cryptography.CngAlgorithm ECDiffieHellmanP384 { get { throw null; } }
public static System.Security.Cryptography.CngAlgorithm ECDiffieHellmanP521 { get { throw null; } }
public static System.Security.Cryptography.CngAlgorithm ECDsa { get { throw null; } }
public static System.Security.Cryptography.CngAlgorithm ECDsaP256 { get { throw null; } }
public static System.Security.Cryptography.CngAlgorithm ECDsaP384 { get { throw null; } }
public static System.Security.Cryptography.CngAlgorithm ECDsaP521 { get { throw null; } }
public static System.Security.Cryptography.CngAlgorithm MD5 { get { throw null; } }
public static System.Security.Cryptography.CngAlgorithm Rsa { get { throw null; } }
public static System.Security.Cryptography.CngAlgorithm Sha1 { get { throw null; } }
public static System.Security.Cryptography.CngAlgorithm Sha256 { get { throw null; } }
public static System.Security.Cryptography.CngAlgorithm Sha384 { get { throw null; } }
public static System.Security.Cryptography.CngAlgorithm Sha512 { get { throw null; } }
public override bool Equals(object obj) { throw null; }
public bool Equals(System.Security.Cryptography.CngAlgorithm other) { throw null; }
public override int GetHashCode() { throw null; }
public static bool operator ==(System.Security.Cryptography.CngAlgorithm left, System.Security.Cryptography.CngAlgorithm right) { throw null; }
public static bool operator !=(System.Security.Cryptography.CngAlgorithm left, System.Security.Cryptography.CngAlgorithm right) { throw null; }
public override string ToString() { throw null; }
}
public sealed partial class CngAlgorithmGroup : System.IEquatable<System.Security.Cryptography.CngAlgorithmGroup>
{
public CngAlgorithmGroup(string algorithmGroup) { }
public string AlgorithmGroup { get { throw null; } }
public static System.Security.Cryptography.CngAlgorithmGroup DiffieHellman { get { throw null; } }
public static System.Security.Cryptography.CngAlgorithmGroup Dsa { get { throw null; } }
public static System.Security.Cryptography.CngAlgorithmGroup ECDiffieHellman { get { throw null; } }
public static System.Security.Cryptography.CngAlgorithmGroup ECDsa { get { throw null; } }
public static System.Security.Cryptography.CngAlgorithmGroup Rsa { get { throw null; } }
public override bool Equals(object obj) { throw null; }
public bool Equals(System.Security.Cryptography.CngAlgorithmGroup other) { throw null; }
public override int GetHashCode() { throw null; }
public static bool operator ==(System.Security.Cryptography.CngAlgorithmGroup left, System.Security.Cryptography.CngAlgorithmGroup right) { throw null; }
public static bool operator !=(System.Security.Cryptography.CngAlgorithmGroup left, System.Security.Cryptography.CngAlgorithmGroup right) { throw null; }
public override string ToString() { throw null; }
}
[System.FlagsAttribute]
public enum CngExportPolicies
{
None = 0,
AllowExport = 1,
AllowPlaintextExport = 2,
AllowArchiving = 4,
AllowPlaintextArchiving = 8,
}
public sealed partial class CngKey : System.IDisposable
{
internal CngKey() { }
public System.Security.Cryptography.CngAlgorithm Algorithm { get { throw null; } }
public System.Security.Cryptography.CngAlgorithmGroup AlgorithmGroup { get { throw null; } }
public System.Security.Cryptography.CngExportPolicies ExportPolicy { get { throw null; } }
public Microsoft.Win32.SafeHandles.SafeNCryptKeyHandle Handle { get { throw null; } }
public bool IsEphemeral { get { throw null; } }
public bool IsMachineKey { get { throw null; } }
public string KeyName { get { throw null; } }
public int KeySize { get { throw null; } }
public System.Security.Cryptography.CngKeyUsages KeyUsage { get { throw null; } }
public System.IntPtr ParentWindowHandle { get { throw null; } set { } }
public System.Security.Cryptography.CngProvider Provider { get { throw null; } }
public Microsoft.Win32.SafeHandles.SafeNCryptProviderHandle ProviderHandle { get { throw null; } }
public System.Security.Cryptography.CngUIPolicy UIPolicy { get { throw null; } }
public string UniqueName { get { throw null; } }
public static System.Security.Cryptography.CngKey Create(System.Security.Cryptography.CngAlgorithm algorithm) { throw null; }
public static System.Security.Cryptography.CngKey Create(System.Security.Cryptography.CngAlgorithm algorithm, string keyName) { throw null; }
public static System.Security.Cryptography.CngKey Create(System.Security.Cryptography.CngAlgorithm algorithm, string keyName, System.Security.Cryptography.CngKeyCreationParameters creationParameters) { throw null; }
public void Delete() { }
public void Dispose() { }
public static bool Exists(string keyName) { throw null; }
public static bool Exists(string keyName, System.Security.Cryptography.CngProvider provider) { throw null; }
public static bool Exists(string keyName, System.Security.Cryptography.CngProvider provider, System.Security.Cryptography.CngKeyOpenOptions options) { throw null; }
public byte[] Export(System.Security.Cryptography.CngKeyBlobFormat format) { throw null; }
public System.Security.Cryptography.CngProperty GetProperty(string name, System.Security.Cryptography.CngPropertyOptions options) { throw null; }
public bool HasProperty(string name, System.Security.Cryptography.CngPropertyOptions options) { throw null; }
public static System.Security.Cryptography.CngKey Import(byte[] keyBlob, System.Security.Cryptography.CngKeyBlobFormat format) { throw null; }
public static System.Security.Cryptography.CngKey Import(byte[] keyBlob, System.Security.Cryptography.CngKeyBlobFormat format, System.Security.Cryptography.CngProvider provider) { throw null; }
public static System.Security.Cryptography.CngKey Open(Microsoft.Win32.SafeHandles.SafeNCryptKeyHandle keyHandle, System.Security.Cryptography.CngKeyHandleOpenOptions keyHandleOpenOptions) { throw null; }
public static System.Security.Cryptography.CngKey Open(string keyName) { throw null; }
public static System.Security.Cryptography.CngKey Open(string keyName, System.Security.Cryptography.CngProvider provider) { throw null; }
public static System.Security.Cryptography.CngKey Open(string keyName, System.Security.Cryptography.CngProvider provider, System.Security.Cryptography.CngKeyOpenOptions openOptions) { throw null; }
public void SetProperty(System.Security.Cryptography.CngProperty property) { }
}
public sealed partial class CngKeyBlobFormat : System.IEquatable<System.Security.Cryptography.CngKeyBlobFormat>
{
public CngKeyBlobFormat(string format) { }
public static System.Security.Cryptography.CngKeyBlobFormat EccFullPrivateBlob { get { throw null; } }
public static System.Security.Cryptography.CngKeyBlobFormat EccFullPublicBlob { get { throw null; } }
public static System.Security.Cryptography.CngKeyBlobFormat EccPrivateBlob { get { throw null; } }
public static System.Security.Cryptography.CngKeyBlobFormat EccPublicBlob { get { throw null; } }
public string Format { get { throw null; } }
public static System.Security.Cryptography.CngKeyBlobFormat GenericPrivateBlob { get { throw null; } }
public static System.Security.Cryptography.CngKeyBlobFormat GenericPublicBlob { get { throw null; } }
public static System.Security.Cryptography.CngKeyBlobFormat OpaqueTransportBlob { get { throw null; } }
public static System.Security.Cryptography.CngKeyBlobFormat Pkcs8PrivateBlob { get { throw null; } }
public override bool Equals(object obj) { throw null; }
public bool Equals(System.Security.Cryptography.CngKeyBlobFormat other) { throw null; }
public override int GetHashCode() { throw null; }
public static bool operator ==(System.Security.Cryptography.CngKeyBlobFormat left, System.Security.Cryptography.CngKeyBlobFormat right) { throw null; }
public static bool operator !=(System.Security.Cryptography.CngKeyBlobFormat left, System.Security.Cryptography.CngKeyBlobFormat right) { throw null; }
public override string ToString() { throw null; }
}
[System.FlagsAttribute]
public enum CngKeyCreationOptions
{
None = 0,
MachineKey = 32,
OverwriteExistingKey = 128,
}
public sealed partial class CngKeyCreationParameters
{
public CngKeyCreationParameters() { }
public System.Security.Cryptography.CngExportPolicies? ExportPolicy { get { throw null; } set { } }
public System.Security.Cryptography.CngKeyCreationOptions KeyCreationOptions { get { throw null; } set { } }
public System.Security.Cryptography.CngKeyUsages? KeyUsage { get { throw null; } set { } }
public System.Security.Cryptography.CngPropertyCollection Parameters { get { throw null; } }
public System.IntPtr ParentWindowHandle { get { throw null; } set { } }
public System.Security.Cryptography.CngProvider Provider { get { throw null; } set { } }
public System.Security.Cryptography.CngUIPolicy UIPolicy { get { throw null; } set { } }
}
[System.FlagsAttribute]
public enum CngKeyHandleOpenOptions
{
None = 0,
EphemeralKey = 1,
}
[System.FlagsAttribute]
public enum CngKeyOpenOptions
{
None = 0,
UserKey = 0,
MachineKey = 32,
Silent = 64,
}
[System.FlagsAttribute]
public enum CngKeyUsages
{
None = 0,
Decryption = 1,
Signing = 2,
KeyAgreement = 4,
AllUsages = 16777215,
}
public partial struct CngProperty : System.IEquatable<System.Security.Cryptography.CngProperty>
{
private object _dummy;
private int _dummyPrimitive;
public CngProperty(string name, byte[] value, System.Security.Cryptography.CngPropertyOptions options) { throw null; }
public readonly string Name { get { throw null; } }
public readonly System.Security.Cryptography.CngPropertyOptions Options { get { throw null; } }
public override bool Equals(object obj) { throw null; }
public bool Equals(System.Security.Cryptography.CngProperty other) { throw null; }
public override int GetHashCode() { throw null; }
public byte[] GetValue() { throw null; }
public static bool operator ==(System.Security.Cryptography.CngProperty left, System.Security.Cryptography.CngProperty right) { throw null; }
public static bool operator !=(System.Security.Cryptography.CngProperty left, System.Security.Cryptography.CngProperty right) { throw null; }
}
public sealed partial class CngPropertyCollection : System.Collections.ObjectModel.Collection<System.Security.Cryptography.CngProperty>
{
public CngPropertyCollection() { }
}
[System.FlagsAttribute]
public enum CngPropertyOptions
{
Persist = -2147483648,
None = 0,
CustomProperty = 1073741824,
}
public sealed partial class CngProvider : System.IEquatable<System.Security.Cryptography.CngProvider>
{
public CngProvider(string provider) { }
public static System.Security.Cryptography.CngProvider MicrosoftSmartCardKeyStorageProvider { get { throw null; } }
public static System.Security.Cryptography.CngProvider MicrosoftSoftwareKeyStorageProvider { get { throw null; } }
public string Provider { get { throw null; } }
public override bool Equals(object obj) { throw null; }
public bool Equals(System.Security.Cryptography.CngProvider other) { throw null; }
public override int GetHashCode() { throw null; }
public static bool operator ==(System.Security.Cryptography.CngProvider left, System.Security.Cryptography.CngProvider right) { throw null; }
public static bool operator !=(System.Security.Cryptography.CngProvider left, System.Security.Cryptography.CngProvider right) { throw null; }
public override string ToString() { throw null; }
}
public sealed partial class CngUIPolicy
{
public CngUIPolicy(System.Security.Cryptography.CngUIProtectionLevels protectionLevel) { }
public CngUIPolicy(System.Security.Cryptography.CngUIProtectionLevels protectionLevel, string friendlyName) { }
public CngUIPolicy(System.Security.Cryptography.CngUIProtectionLevels protectionLevel, string friendlyName, string description) { }
public CngUIPolicy(System.Security.Cryptography.CngUIProtectionLevels protectionLevel, string friendlyName, string description, string useContext) { }
public CngUIPolicy(System.Security.Cryptography.CngUIProtectionLevels protectionLevel, string friendlyName, string description, string useContext, string creationTitle) { }
public string CreationTitle { get { throw null; } }
public string Description { get { throw null; } }
public string FriendlyName { get { throw null; } }
public System.Security.Cryptography.CngUIProtectionLevels ProtectionLevel { get { throw null; } }
public string UseContext { get { throw null; } }
}
[System.FlagsAttribute]
public enum CngUIProtectionLevels
{
None = 0,
ProtectKey = 1,
ForceHighProtection = 2,
}
public sealed partial class DSACng : System.Security.Cryptography.DSA
{
public DSACng() { }
public DSACng(int keySize) { }
public DSACng(System.Security.Cryptography.CngKey key) { }
public System.Security.Cryptography.CngKey Key { get { throw null; } }
public override string KeyExchangeAlgorithm { get { throw null; } }
public override System.Security.Cryptography.KeySizes[] LegalKeySizes { get { throw null; } }
public override string SignatureAlgorithm { get { throw null; } }
public override byte[] CreateSignature(byte[] rgbHash) { throw null; }
protected override void Dispose(bool disposing) { }
public override System.Security.Cryptography.DSAParameters ExportParameters(bool includePrivateParameters) { throw null; }
#if FEATURE_DSA_HASHDATA
protected override byte[] HashData(byte[] data, int offset, int count, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; }
protected override byte[] HashData(System.IO.Stream data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; }
#endif
public override void ImportParameters(System.Security.Cryptography.DSAParameters parameters) { }
public override bool VerifySignature(byte[] rgbHash, byte[] rgbSignature) { throw null; }
}
public sealed partial class ECDiffieHellmanCng : System.Security.Cryptography.ECDiffieHellman
{
public ECDiffieHellmanCng() { }
public ECDiffieHellmanCng(int keySize) { }
public ECDiffieHellmanCng(System.Security.Cryptography.CngKey key) { }
#if FEATURE_ECPARAMETERS
public ECDiffieHellmanCng(System.Security.Cryptography.ECCurve curve) { }
#endif
public System.Security.Cryptography.CngAlgorithm HashAlgorithm { get { throw null; } set { } }
public byte[] HmacKey { get { throw null; } set { } }
public System.Security.Cryptography.CngKey Key { get { throw null; } }
public System.Security.Cryptography.ECDiffieHellmanKeyDerivationFunction KeyDerivationFunction { get { throw null; } set { } }
public override int KeySize { get { throw null; } set { } }
public byte[] Label { get { throw null; } set { } }
public override System.Security.Cryptography.ECDiffieHellmanPublicKey PublicKey { get { throw null; } }
public byte[] SecretAppend { get { throw null; } set { } }
public byte[] SecretPrepend { get { throw null; } set { } }
public byte[] Seed { get { throw null; } set { } }
public bool UseSecretAgreementAsHmacKey { get { throw null; } }
#if FEATURE_ECDH_DERIVEFROM
public override byte[] DeriveKeyFromHash(System.Security.Cryptography.ECDiffieHellmanPublicKey otherPartyPublicKey, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, byte[] secretPrepend, byte[] secretAppend) { throw null; }
public override byte[] DeriveKeyFromHmac(System.Security.Cryptography.ECDiffieHellmanPublicKey otherPartyPublicKey, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, byte[] hmacKey, byte[] secretPrepend, byte[] secretAppend) { throw null; }
#endif
public byte[] DeriveKeyMaterial(System.Security.Cryptography.CngKey otherPartyPublicKey) { throw null; }
public override byte[] DeriveKeyMaterial(System.Security.Cryptography.ECDiffieHellmanPublicKey otherPartyPublicKey) { throw null; }
#if FEATURE_ECDH_DERIVEFROM
public override byte[] DeriveKeyTls(System.Security.Cryptography.ECDiffieHellmanPublicKey otherPartyPublicKey, byte[] prfLabel, byte[] prfSeed) { throw null; }
#endif
public Microsoft.Win32.SafeHandles.SafeNCryptSecretHandle DeriveSecretAgreementHandle(System.Security.Cryptography.CngKey otherPartyPublicKey) { throw null; }
public Microsoft.Win32.SafeHandles.SafeNCryptSecretHandle DeriveSecretAgreementHandle(System.Security.Cryptography.ECDiffieHellmanPublicKey otherPartyPublicKey) { throw null; }
protected override void Dispose(bool disposing) { }
#if FEATURE_ECPARAMETERS
public override System.Security.Cryptography.ECParameters ExportExplicitParameters(bool includePrivateParameters) { throw null; }
public override System.Security.Cryptography.ECParameters ExportParameters(bool includePrivateParameters) { throw null; }
#endif
public void FromXmlString(string xml, System.Security.Cryptography.ECKeyXmlFormat format) { }
#if FEATURE_ECPARAMETERS
public override void GenerateKey(System.Security.Cryptography.ECCurve curve) { }
public override void ImportParameters(System.Security.Cryptography.ECParameters parameters) { }
#endif
public string ToXmlString(System.Security.Cryptography.ECKeyXmlFormat format) { throw null; }
}
public sealed partial class ECDiffieHellmanCngPublicKey : System.Security.Cryptography.ECDiffieHellmanPublicKey
{
// ECDiffieHellmanPublicKey parameter-less ctor only exist on .NET Framework 4.7+
private ECDiffieHellmanCngPublicKey() : base(null) { }
public System.Security.Cryptography.CngKeyBlobFormat BlobFormat { get { throw null; } }
protected override void Dispose(bool disposing) { }
#if FEATURE_ECPARAMETERS
public override System.Security.Cryptography.ECParameters ExportExplicitParameters() { throw null; }
public override System.Security.Cryptography.ECParameters ExportParameters() { throw null; }
#endif
public static System.Security.Cryptography.ECDiffieHellmanPublicKey FromByteArray(byte[] publicKeyBlob, System.Security.Cryptography.CngKeyBlobFormat format) { throw null; }
public static System.Security.Cryptography.ECDiffieHellmanCngPublicKey FromXmlString(string xml) { throw null; }
public System.Security.Cryptography.CngKey Import() { throw null; }
public override string ToXmlString() { throw null; }
}
public enum ECDiffieHellmanKeyDerivationFunction
{
Hash = 0,
Hmac = 1,
Tls = 2,
}
public sealed partial class ECDsaCng : System.Security.Cryptography.ECDsa
{
public ECDsaCng() { }
public ECDsaCng(int keySize) { }
public ECDsaCng(System.Security.Cryptography.CngKey key) { }
#if FEATURE_ECPARAMETERS // types missing from .NET Framework and net462 targeting pack
public ECDsaCng(System.Security.Cryptography.ECCurve curve) { }
#endif
public System.Security.Cryptography.CngAlgorithm HashAlgorithm { get { throw null; } set { } }
public System.Security.Cryptography.CngKey Key { get { throw null; } }
public override int KeySize { get { throw null; } set { } }
public override System.Security.Cryptography.KeySizes[] LegalKeySizes { get { throw null; } }
protected override void Dispose(bool disposing) { }
#if FEATURE_ECPARAMETERS // types missing from .NET Framework and net462 targeting pack
public override System.Security.Cryptography.ECParameters ExportExplicitParameters(bool includePrivateParameters) { throw null; }
public override System.Security.Cryptography.ECParameters ExportParameters(bool includePrivateParameters) { throw null; }
#endif
public void FromXmlString(string xml, System.Security.Cryptography.ECKeyXmlFormat format) { }
#if FEATURE_ECPARAMETERS // types missing from .NET Framework and net462 targeting pack
public override void GenerateKey(System.Security.Cryptography.ECCurve curve) { }
#endif
protected override byte[] HashData(byte[] data, int offset, int count, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; }
protected override byte[] HashData(System.IO.Stream data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; }
#if FEATURE_ECPARAMETERS // types missing from .NET Framework and net462 targeting pack
public override void ImportParameters(System.Security.Cryptography.ECParameters parameters) { }
#endif
public byte[] SignData(byte[] data) { throw null; }
public byte[] SignData(byte[] data, int offset, int count) { throw null; }
public byte[] SignData(System.IO.Stream data) { throw null; }
public override byte[] SignHash(byte[] hash) { throw null; }
public string ToXmlString(System.Security.Cryptography.ECKeyXmlFormat format) { throw null; }
public bool VerifyData(byte[] data, byte[] signature) { throw null; }
public bool VerifyData(byte[] data, int offset, int count, byte[] signature) { throw null; }
public bool VerifyData(System.IO.Stream data, byte[] signature) { throw null; }
public override bool VerifyHash(byte[] hash, byte[] signature) { throw null; }
}
public enum ECKeyXmlFormat
{
Rfc4050 = 0,
}
public sealed partial class RSACng : System.Security.Cryptography.RSA
{
public RSACng() { }
public RSACng(int keySize) { }
public RSACng(System.Security.Cryptography.CngKey key) { }
public System.Security.Cryptography.CngKey Key { get { throw null; } }
public override System.Security.Cryptography.KeySizes[] LegalKeySizes { get { throw null; } }
public override byte[] Decrypt(byte[] data, System.Security.Cryptography.RSAEncryptionPadding padding) { throw null; }
protected override void Dispose(bool disposing) { }
public override byte[] Encrypt(byte[] data, System.Security.Cryptography.RSAEncryptionPadding padding) { throw null; }
public override System.Security.Cryptography.RSAParameters ExportParameters(bool includePrivateParameters) { throw null; }
protected override byte[] HashData(byte[] data, int offset, int count, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; }
protected override byte[] HashData(System.IO.Stream data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { throw null; }
public override void ImportParameters(System.Security.Cryptography.RSAParameters parameters) { }
public override byte[] SignHash(byte[] hash, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { throw null; }
public override bool VerifyHash(byte[] hash, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { throw null; }
}
public sealed partial class TripleDESCng : System.Security.Cryptography.TripleDES
{
public TripleDESCng() { }
public TripleDESCng(string keyName) { }
public TripleDESCng(string keyName, System.Security.Cryptography.CngProvider provider) { }
public TripleDESCng(string keyName, System.Security.Cryptography.CngProvider provider, System.Security.Cryptography.CngKeyOpenOptions openOptions) { }
public override byte[] Key { get { throw null; } set { } }
public override int KeySize { get { throw null; } set { } }
public override System.Security.Cryptography.ICryptoTransform CreateDecryptor() { throw null; }
public override System.Security.Cryptography.ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[] rgbIV) { throw null; }
public override System.Security.Cryptography.ICryptoTransform CreateEncryptor() { throw null; }
public override System.Security.Cryptography.ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[] rgbIV) { throw null; }
protected override void Dispose(bool disposing) { }
public override void GenerateIV() { }
public override void GenerateKey() { }
}
}
| 69.765133 | 260 | 0.722625 | [
"MIT"
] | CoffeeFlux/runtime | src/libraries/System.Security.Cryptography.Cng/ref/System.Security.Cryptography.Cng.cs | 28,813 | C# |
namespace FactoryMethod
{
// The Creator class declares the factory method that is supposed to return
// an object of a Product class. The Creator's subclasses usually provide
// the implementation of this method.
public abstract class Creator
{
// Note that the Creator may also provide some default implementation of
// the factory method.
public abstract IProduct FactoryMethod();
// Also note that, despite its name, the Creator's primary
// responsibility is not creating products. Usually, it contains some
// core business logic that relies on Product objects, returned by the
// factory method. Subclasses can indirectly change that business logic
// by overriding the factory method and returning a different type of
// product from it.
public string SomeOperation()
{
// Call the factory method to create a Product object.
var product = FactoryMethod();
// Now, use the product.
var result = "Creator: The same creator's code has just worked with "
+ product.Operation();
return result;
}
}
}
| 40.066667 | 81 | 0.645591 | [
"MIT"
] | BorisLechev/Design-Patterns | CreationalPatterns/Factory/Creator.cs | 1,204 | 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 greengrass-2017-06-07.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.Greengrass.Model
{
/// <summary>
/// This is the response object from the UpdateGroup operation.
/// </summary>
public partial class UpdateGroupResponse : AmazonWebServiceResponse
{
}
} | 29.236842 | 108 | 0.732673 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/Greengrass/Generated/Model/UpdateGroupResponse.cs | 1,111 | C# |
using System.ComponentModel.DataAnnotations;
namespace MovieTickets.Web.ViewModels.Account
{
using static Data.DataConstants;
public class LoginViewModel
{
[Display(Name =DisplayEmail)]
[Required(ErrorMessage =EmailError)]
public string Email { get; set; }
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
}
}
| 23.882353 | 45 | 0.660099 | [
"MIT"
] | kivanov22/MovieTickets | MovieTickets/MovieTickets/ViewModels/Account/LoginViewModel.cs | 408 | C# |
namespace GeometricAlgebraStructuresLib.Storage
{
public static class GaMultivectorStorageUtils
{
public static T[] GetCopyOfArray<T>(this T[] inputArray)
{
var outputArray = new T[inputArray.Length];
inputArray.CopyTo(outputArray, 0);
return outputArray;
}
}
} | 24.857143 | 64 | 0.600575 | [
"MIT"
] | ga-explorer/GMac | GeometricAlgebraStructuresLib/GeometricAlgebraStructuresLib/Storage/GaMultivectorStorageUtils.cs | 350 | C# |
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
namespace Button_Samp
{
public partial class Page1 : Page
{
private ToolTip _ttp;
// This function checks the language filter settings to see which code to filter and also grays out tabs with no content
public void CheckLang(object sender, EventArgs e)
{
if (xcsharpCheck.Content == null) // grays out xaml + c# tab
{
xamlcsharp.Background = Brushes.Gainsboro;
xamlcsharp.Foreground = Brushes.White;
_ttp = new ToolTip();
ToolTipService.SetShowOnDisabled(xamlcsharp, true);
_ttp.Content = "This sample is not available in XAML + C#.";
xamlcsharp.ToolTip = (_ttp);
xamlcsharp.IsEnabled = false;
}
else if (xcsharpCheck.Content != null)
{
xamlcsharp.IsEnabled = true;
}
if (xvbCheck.Content == null) // grays out xaml + vb tab
{
xamlvb.Background = Brushes.Gainsboro;
xamlvb.Foreground = Brushes.White;
_ttp = new ToolTip();
ToolTipService.SetShowOnDisabled(xamlvb, true);
_ttp.Content = "This sample is not available in XAML + Visual Basic.NET";
xamlvb.ToolTip = (_ttp);
xamlvb.IsEnabled = false;
}
else if (xvbCheck.Content != null)
{
xamlvb.IsEnabled = true;
}
if (xaml.Content == null) // grays out xaml
{
xaml.IsEnabled = false;
xaml.Background = Brushes.Gainsboro;
xaml.Foreground = Brushes.White;
_ttp = new ToolTip();
ToolTipService.SetShowOnDisabled(xaml, true);
_ttp.Content = "This sample is not available in XAML.";
xaml.ToolTip = (_ttp);
}
else if (xaml.Content != null)
{
xaml.IsEnabled = true;
}
if (csharp.Content == null) // grays out c#
{
csharp.IsEnabled = false;
csharp.Background = Brushes.Gainsboro;
csharp.Foreground = Brushes.White;
_ttp = new ToolTip();
ToolTipService.SetShowOnDisabled(csharp, true);
_ttp.Content = "This sample is not available in C#.";
csharp.ToolTip = (_ttp);
}
else if (csharp.Content != null)
{
csharp.IsEnabled = true;
}
if (vb.Content == null) // grays out vb
{
vb.IsEnabled = false;
vb.Background = Brushes.Gainsboro;
vb.Foreground = Brushes.White;
_ttp = new ToolTip();
ToolTipService.SetShowOnDisabled(vb, true);
_ttp.Content = "This sample is not available in Visual Basic.NET.";
vb.ToolTip = (_ttp);
}
else if (vb.Content != null)
{
vb.IsEnabled = true;
}
if (managedcpp.Content == null) // grays out cpp
{
managedcpp.IsEnabled = false;
managedcpp.Background = Brushes.Gainsboro;
managedcpp.Foreground = Brushes.White;
_ttp = new ToolTip();
ToolTipService.SetShowOnDisabled(managedcpp, true);
_ttp.Content = "This sample is not available in Managed C++.";
managedcpp.ToolTip = (_ttp);
}
else if (managedcpp.Content != null)
{
managedcpp.IsEnabled = true;
}
if (Welcome.Page1.MyDouble == 1) // XAML only
{
xaml.Visibility = Visibility.Visible;
csharp.Visibility = Visibility.Collapsed;
vb.Visibility = Visibility.Collapsed;
managedcpp.Visibility = Visibility.Collapsed;
xamlcsharp.Visibility = Visibility.Collapsed;
xamlvb.Visibility = Visibility.Collapsed;
}
else if (Welcome.Page1.MyDouble == 2) // CSharp
{
csharp.Visibility = Visibility.Visible;
xaml.Visibility = Visibility.Collapsed;
vb.Visibility = Visibility.Collapsed;
managedcpp.Visibility = Visibility.Collapsed;
xamlcsharp.Visibility = Visibility.Collapsed;
xamlvb.Visibility = Visibility.Collapsed;
}
else if (Welcome.Page1.MyDouble == 3) // Visual Basic
{
vb.Visibility = Visibility.Visible;
xaml.Visibility = Visibility.Collapsed;
csharp.Visibility = Visibility.Collapsed;
managedcpp.Visibility = Visibility.Collapsed;
xamlcsharp.Visibility = Visibility.Collapsed;
xamlvb.Visibility = Visibility.Collapsed;
}
else if (Welcome.Page1.MyDouble == 4) // Managed CPP
{
managedcpp.Visibility = Visibility.Visible;
xaml.Visibility = Visibility.Collapsed;
csharp.Visibility = Visibility.Collapsed;
vb.Visibility = Visibility.Collapsed;
xamlcsharp.Visibility = Visibility.Collapsed;
xamlvb.Visibility = Visibility.Collapsed;
}
else if (Welcome.Page1.MyDouble == 5) // No Filter
{
xaml.Visibility = Visibility.Visible;
csharp.Visibility = Visibility.Visible;
vb.Visibility = Visibility.Visible;
managedcpp.Visibility = Visibility.Visible;
xamlcsharp.Visibility = Visibility.Visible;
xamlvb.Visibility = Visibility.Visible;
}
else if (Welcome.Page1.MyDouble == 6) // XAML + CSharp
{
xaml.Visibility = Visibility.Collapsed;
csharp.Visibility = Visibility.Collapsed;
vb.Visibility = Visibility.Collapsed;
managedcpp.Visibility = Visibility.Collapsed;
xamlcsharp.Visibility = Visibility.Visible;
xamlvb.Visibility = Visibility.Collapsed;
}
else if (Welcome.Page1.MyDouble == 7) // XAML + VB
{
xaml.Visibility = Visibility.Collapsed;
csharp.Visibility = Visibility.Collapsed;
vb.Visibility = Visibility.Collapsed;
managedcpp.Visibility = Visibility.Collapsed;
xamlcsharp.Visibility = Visibility.Collapsed;
xamlvb.Visibility = Visibility.Visible;
}
}
}
} | 41.467836 | 128 | 0.52898 | [
"MIT"
] | 21pages/WPF-Samples | Getting Started/Concepts/samps/button_samp.xaml.cs | 7,093 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/strmif.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved.
using NUnit.Framework;
using System;
using System.Runtime.InteropServices;
using static TerraFX.Interop.Windows;
namespace TerraFX.Interop.UnitTests
{
/// <summary>Provides validation of the <see cref="IDDrawExclModeVideoCallback" /> struct.</summary>
public static unsafe partial class IDDrawExclModeVideoCallbackTests
{
/// <summary>Validates that the <see cref="Guid" /> of the <see cref="IDDrawExclModeVideoCallback" /> struct is correct.</summary>
[Test]
public static void GuidOfTest()
{
Assert.That(typeof(IDDrawExclModeVideoCallback).GUID, Is.EqualTo(IID_IDDrawExclModeVideoCallback));
}
/// <summary>Validates that the <see cref="IDDrawExclModeVideoCallback" /> struct is blittable.</summary>
[Test]
public static void IsBlittableTest()
{
Assert.That(Marshal.SizeOf<IDDrawExclModeVideoCallback>(), Is.EqualTo(sizeof(IDDrawExclModeVideoCallback)));
}
/// <summary>Validates that the <see cref="IDDrawExclModeVideoCallback" /> struct has the right <see cref="LayoutKind" />.</summary>
[Test]
public static void IsLayoutSequentialTest()
{
Assert.That(typeof(IDDrawExclModeVideoCallback).IsLayoutSequential, Is.True);
}
/// <summary>Validates that the <see cref="IDDrawExclModeVideoCallback" /> struct has the correct size.</summary>
[Test]
public static void SizeOfTest()
{
if (Environment.Is64BitProcess)
{
Assert.That(sizeof(IDDrawExclModeVideoCallback), Is.EqualTo(8));
}
else
{
Assert.That(sizeof(IDDrawExclModeVideoCallback), Is.EqualTo(4));
}
}
}
}
| 39.730769 | 145 | 0.661181 | [
"MIT"
] | DaZombieKiller/terrafx.interop.windows | tests/Interop/Windows/um/strmif/IDDrawExclModeVideoCallbackTests.cs | 2,068 | C# |
using System.Collections.Generic;
namespace IronText.Algorithm
{
sealed internal class MutableIntervalIntSet : IntervalIntSetBase
{
public MutableIntervalIntSet(IntSetType setType) : base(setType) { }
public override IntSet CompleteAndDestroy()
{
var result = new IntervalIntSet(setType, this.intervals);
this.intervals = new List<IntInterval>();
UpdateHashAndBounds();
return result;
}
public override MutableIntSet EditCopy()
{
var result = new MutableIntervalIntSet(setType);
result.AddAll(this);
return result;
}
}
}
| 27.08 | 76 | 0.615953 | [
"Apache-2.0"
] | sucaba/IronTextLibrary | Src/IronText.Core/Algorithm/IntegerSets/MutableIntervalIntSet.cs | 679 | C# |
using Rbac.Core;
using PetaPoco;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Rbac.Entity
{
[Serializable]
[TableName("Base_Organize")]
[PrimaryKey("Id")]
[Description("组织机构")]
[Key("Id")]
public class BaseOrganize
{
/// <summary>
/// 机构主键
/// </summary>
[Description("机构主键")]
public string Id { get; set; }
/// <summary>
/// 上级机构主键
/// </summary>
[Description("上级机构主键")]
public string ParentId { get; set; }
/// <summary>
/// 机构名称
/// </summary>
[Description("机构名称")]
public string Name { get; set; }
/// <summary>
/// 机构编码
/// </summary>
[Description("机构编码")]
public string Code { get; set; }
/// <summary>
/// 机构描述
/// </summary>
[Description("机构描述")]
public string Description { get; set; }
/// <summary>
/// 机构类型
/// </summary>
[Description("机构类型")]
public int Type { get; set; }
/// <summary>
/// 是否启用
/// </summary>
[Description("是否启用")]
public int Enabled { get; set; }
/// <summary>
/// 排序值
/// </summary>
[Description("排序值")]
public int SortCode { get; set; }
/// <summary>
/// 机构全称
/// </summary>
[Description("机构全称")]
public string FullName { get; set; }
/// <summary>
/// 办公地点
/// </summary>
[Description("办公地点")]
public string Office { get; set; }
/// <summary>
/// 管理员手机号码
/// </summary>
[Description("管理员手机号码")]
public string MobilePhone { get; set; }
/// <summary>
/// 创建人主键
/// </summary>
[Description("创建人主键")]
public string CreateUserId { get; set; }
/// <summary>
/// 创建日期
/// </summary>
[Description("创建日期")]
public string CreateDate { get; set; }
/// <summary>
/// 修改人主键
/// </summary>
[Description("修改人主键")]
public string ModifyUserId { get; set; }
/// <summary>
/// 修改时间
/// </summary>
[Description("修改时间")]
public string ModifyDate { get; set; }
/// <summary>
/// 上级机构名称
/// </summary>
[ResultColumn]
public string ParentName { get; set; }
/// <summary>
/// 节点选中
/// </summary>
[ResultColumn]
public bool isChecked { get; set; }
/// <summary>
/// 子节点个数
/// </summary>
[ResultColumn]
public string Amount { get; set; }
/// <summary>
/// 是否是叶子节点
/// </summary>
[ResultColumn]
public bool isleaf { get; set; }
}
}
| 26.362069 | 49 | 0.446043 | [
"MIT"
] | codeyu/codeyu.rbac.web | src/RbacWeb/Rbac.Entity/BaseOrganize.cs | 3,376 | C# |
using System;
public class Sarsa : IReinforcementLearning
{
private readonly double[][] _q;
public double LearningRate { get; set; }
public double DiscountFactor { get; set; }
public IExplorationPolicy ExplorationPolicy { get; set; }
public Sarsa(int stateCount, int actionCount, IExplorationPolicy explorationPolicy, double learningRate = 0.1,
double discountFactor = 0.9, bool initializeRandom = false)
{
StateCount = stateCount;
ActionCount = actionCount;
ExplorationPolicy = explorationPolicy;
LearningRate = learningRate;
DiscountFactor = discountFactor;
_q = new double[stateCount][];
for (var i = 0; i < stateCount; i++) {
_q[i] = new double[actionCount];
}
if (initializeRandom) {
var random = new Random();
for (var i = 0; i < stateCount; i++) {
for (var j = 0; j < actionCount; j++) {
_q[i][j] = random.NextDouble();
}
}
}
}
public int CurrentState { get; private set; }
public int SelectedAction { get; private set; }
public int StateCount { get; }
public int ActionCount { get; }
public double Fitness { get; set; }
public void Begin(int state)
{
CurrentState = state;
SelectedAction = ExplorationPolicy.SelectAction(_q[CurrentState]);
Fitness = 0.0;
}
public void Step(double reward, int nextState)
{
var nextAction = ExplorationPolicy.SelectAction(_q[nextState]);
var target = reward + DiscountFactor * _q[nextState][nextAction];
var delta = target - _q[CurrentState][SelectedAction];
_q[CurrentState][SelectedAction] += LearningRate * delta;
CurrentState = nextState;
SelectedAction = ExplorationPolicy.SelectAction(_q[CurrentState]);
Fitness += reward;
}
} | 29.216667 | 112 | 0.67028 | [
"MIT"
] | paidgeek/LayeredHybridIntelligentAgents | Assets/Scripts/Brain/ReinforcementLearning/Sarsa.cs | 1,755 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Text.RegularExpressions;
using System.Linq;
namespace BigPlane {
/// <summary>
/// 从文件中来的数据记录
/// </summary>
public interface IRecord {
int id { get; }
bool isEmpty();
void InitFromLine(string s);
}
/// <summary>
/// 逗号分隔的行列表,会忽略//开头的行,字符串中间的//往后的内容也会被忽略
/// </summary>
public static class SimpleCsv {
const string pattern = @"[\r\n]|//+.*[\r\n]";
static SimpleCsv(){}
/// <summary>
/// 根据一个res名字载入资源
/// </summary>
/// <returns></returns>
public static string[] OpenCsv(string path) {
TextAsset text = Resources.Load<TextAsset>(path);
if (text != null)
return OpenCsv(text);
else
throw new UnityException($"读取文件错误:{path}");
}
/// <summary>
/// 获取csv的所有数据
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public static string[] OpenCsv(TextAsset text) {
Regex reg = new Regex(pattern);
string[] lines = reg.Split(text.text);
return lines.Where((x) => !string.IsNullOrEmpty(x)).ToArray<string>();
}
public static Dictionary<int, T> OpenCsvAs<T>(string path) where T : IRecord, new() {
TextAsset text = Resources.Load<TextAsset>(path);
if (text != null)
return OpenCsvAs<T>(text);
else
throw new UnityException($"读取文件错误:{path}");
}
public static Dictionary<int,T> OpenCsvAs<T>(TextAsset text) where T:IRecord,new() {
Dictionary<int, T> dict = new Dictionary<int, T>();
string[] lines = OpenCsv(text);
if (lines.Length == 0)
throw new UnityException($"{text.name}没有数据");
for (int i = 0; i < lines.Length; i++) {
T t = new T();
t.InitFromLine(lines[i]);
dict.Add(t.id, t);
}
return dict;
}
public static Dictionary<string, string> OpenCsvAsKV(TextAsset text) {
Dictionary<string, string> dict = new Dictionary<string, string>();
string[] lines = OpenCsv(text);
if(lines.Length==0)
throw new UnityException($"{text.name}没有数据");
string[] cells;
for (int i = 0; i < lines.Length; i++) {
cells = lines[i].Split(',');
dict.Add(cells[0], cells[1]);
}
return dict;
}
}
} | 28 | 93 | 0.505952 | [
"Apache-2.0"
] | BigWan/BigGame_WeChatPlane | Assets/Scripts/ReadCsv.cs | 2,846 | C# |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using OpenMetaverse;
using OpenSim.Framework;
using System;
using System.Collections.Generic;
namespace OpenSim.Data
{
public class RegionData
{
public UUID RegionID;
public UUID ScopeID;
public string RegionName;
/// <summary>
/// The position in meters of this region.
/// </summary>
public int posX;
/// <summary>
/// The position in meters of this region.
/// </summary>
public int posY;
public int sizeX;
public int sizeY;
/// <summary>
/// Return the x-coordinate of this region in region units.
/// </summary>
public int coordX { get { return (int)Util.WorldToRegionLoc((uint)posX); } }
/// <summary>
/// Return the y-coordinate of this region in region units.
/// </summary>
public int coordY { get { return (int)Util.WorldToRegionLoc((uint)posY); } }
public Dictionary<string, object> Data;
}
/// <summary>
/// An interface for connecting to the authentication datastore
/// </summary>
public interface IRegionData
{
RegionData Get(UUID regionID, UUID ScopeID);
List<RegionData> Get(string regionName, UUID ScopeID);
RegionData GetSpecific(string regionName, UUID ScopeID);
RegionData Get(int x, int y, UUID ScopeID);
List<RegionData> Get(int xStart, int yStart, int xEnd, int yEnd, UUID ScopeID);
bool Store(RegionData data);
bool SetDataItem(UUID principalID, string item, string value);
bool Delete(UUID regionID);
List<RegionData> GetDefaultRegions(UUID scopeID);
List<RegionData> GetDefaultHypergridRegions(UUID scopeID);
List<RegionData> GetFallbackRegions(UUID scopeID, int x, int y);
List<RegionData> GetHyperlinks(UUID scopeID);
}
public class RegionDataDistanceCompare : IComparer<RegionData>
{
private Vector2 m_origin;
public RegionDataDistanceCompare(int x, int y)
{
m_origin = new Vector2(x, y);
}
public int Compare(RegionData regionA, RegionData regionB)
{
Vector2 vectorA = new Vector2(regionA.posX, regionA.posY);
Vector2 vectorB = new Vector2(regionB.posX, regionB.posY);
return Math.Sign(VectorDistance(m_origin, vectorA) - VectorDistance(m_origin, vectorB));
}
private float VectorDistance(Vector2 x, Vector2 y)
{
return (x - y).Length();
}
}
}
| 36.911504 | 100 | 0.671542 | [
"BSD-3-Clause"
] | mdickson/opensim | OpenSim/Data/IRegionData.cs | 4,171 | C# |
using Microsoft.Extensions.CommandLineUtils;
namespace BoxCLI.CommandUtilities.CommandOptions
{
public static class FieldsOption
{
public static CommandOption ConfigureOption(CommandLineApplication command)
=> command.Option("--fields <FIELDS>", "The fields to include in the Box response, separate each field with a comma", CommandOptionType.SingleValue);
}
} | 39.3 | 161 | 0.755725 | [
"Apache-2.0"
] | TinLe/boxcli | BoxCLI/CommandUtilities/CommandOptions/FieldsOption.cs | 393 | C# |
using System;
using NUnit.Framework;
using Xamarin.Forms.Core.UnitTests;
namespace Xamarin.Forms.Xaml.UnitTests
{
[TestFixture]
public class HRTests
{
[SetUp]
public void Setup()
{
Device.PlatformServices = new MockPlatformServices();
Xamarin.Forms.Internals.Registrar.RegisterAll(new Type[0]);
Application.Current = null;
}
[TearDown]
public void TearDown()
{
Device.PlatformServices = null;
XamlLoader.FallbackTypeResolver = null;
XamlLoader.ValueCreatedCallback = null;
XamlLoader.InstantiationFailedCallback = null;
Forms.Internals.ResourceLoader.ExceptionHandler2 = null;
#pragma warning disable 0618
Internals.XamlLoader.DoNotThrowOnExceptions = false;
#pragma warning restore 0618
Application.ClearCurrent();
}
[Test]
public void LoadResources()
{
var app = @"
<Application xmlns=""http://xamarin.com/schemas/2014/forms""
xmlns:x=""http://schemas.microsoft.com/winfx/2009/xaml"">
<Application.Resources>
<ResourceDictionary>
<Color x:Key=""almostPink"">HotPink</Color>
</ResourceDictionary>
</Application.Resources>
</Application>
";
Assert.That(Application.Current, Is.Null);
var mockApplication = new MockApplication();
var rd = XamlLoader.LoadResources(app, mockApplication);
Assert.That(rd, Is.TypeOf<ResourceDictionary>());
Assert.That(((ResourceDictionary)rd).Count, Is.EqualTo(1));
//check that the live app hasn't ben modified
Assert.That(Application.Current, Is.EqualTo(mockApplication));
Assert.That(Application.Current.Resources.Count, Is.EqualTo(0));
}
[Test]
public void LoadMultipleResources()
{
var app = @"
<Application xmlns=""http://xamarin.com/schemas/2014/forms""
xmlns:x=""http://schemas.microsoft.com/winfx/2009/xaml"">
<Application.Resources>
<Color x:Key=""almostPink"">HotPink</Color>
<Color x:Key=""yellowOrGreen"">Chartreuse</Color>
</Application.Resources>
</Application>
";
Assert.That(Application.Current, Is.Null);
var mockApplication = new MockApplication();
var rd = XamlLoader.LoadResources(app, mockApplication);
Assert.That(rd, Is.TypeOf<ResourceDictionary>());
Assert.That(((ResourceDictionary)rd).Count, Is.EqualTo(2));
//check that the live app hasn't ben modified
Assert.That(Application.Current, Is.EqualTo(mockApplication));
Assert.That(Application.Current.Resources.Count, Is.EqualTo(0));
}
[Test]
public void LoadSingleImplicitResources()
{
var app = @"
<Application xmlns=""http://xamarin.com/schemas/2014/forms""
xmlns:x=""http://schemas.microsoft.com/winfx/2009/xaml"">
<Application.Resources>
<Color x:Key=""almostPink"">HotPink</Color>
</Application.Resources>
</Application>
";
Assert.That(Application.Current, Is.Null);
var mockApplication = new MockApplication();
var rd = XamlLoader.LoadResources(app, mockApplication);
Assert.That(rd, Is.TypeOf<ResourceDictionary>());
Assert.That(((ResourceDictionary)rd).Count, Is.EqualTo(1));
//check that the live app hasn't ben modified
Assert.That(Application.Current, Is.EqualTo(mockApplication));
Assert.That(Application.Current.Resources.Count, Is.EqualTo(0));
}
}
}
| 31.259615 | 67 | 0.708705 | [
"MIT"
] | 07101994/Xamarin.Forms | Xamarin.Forms.Xaml.UnitTests/HRTests.cs | 3,253 | C# |
using System.Collections.Generic;
using Horizon.Payment.Alipay.Response;
namespace Horizon.Payment.Alipay.Request
{
/// <summary>
/// alipay.ebpp.prodmode.reconconf.query
/// </summary>
public class AlipayEbppProdmodeReconconfQueryRequest : IAlipayRequest<AlipayEbppProdmodeReconconfQueryResponse>
{
/// <summary>
/// 对账配置查询接口
/// </summary>
public string BizContent { get; set; }
#region IAlipayRequest Members
private bool needEncrypt = false;
private string apiVersion = "1.0";
private string terminalType;
private string terminalInfo;
private string prodCode;
private string notifyUrl;
private string returnUrl;
private AlipayObject bizModel;
public void SetNeedEncrypt(bool needEncrypt)
{
this.needEncrypt = needEncrypt;
}
public bool GetNeedEncrypt()
{
return needEncrypt;
}
public void SetNotifyUrl(string notifyUrl)
{
this.notifyUrl = notifyUrl;
}
public string GetNotifyUrl()
{
return notifyUrl;
}
public void SetReturnUrl(string returnUrl)
{
this.returnUrl = returnUrl;
}
public string GetReturnUrl()
{
return returnUrl;
}
public void SetTerminalType(string terminalType)
{
this.terminalType = terminalType;
}
public string GetTerminalType()
{
return terminalType;
}
public void SetTerminalInfo(string terminalInfo)
{
this.terminalInfo = terminalInfo;
}
public string GetTerminalInfo()
{
return terminalInfo;
}
public void SetProdCode(string prodCode)
{
this.prodCode = prodCode;
}
public string GetProdCode()
{
return prodCode;
}
public string GetApiName()
{
return "alipay.ebpp.prodmode.reconconf.query";
}
public void SetApiVersion(string apiVersion)
{
this.apiVersion = apiVersion;
}
public string GetApiVersion()
{
return apiVersion;
}
public IDictionary<string, string> GetParameters()
{
var parameters = new AlipayDictionary
{
{ "biz_content", BizContent }
};
return parameters;
}
public AlipayObject GetBizModel()
{
return bizModel;
}
public void SetBizModel(AlipayObject bizModel)
{
this.bizModel = bizModel;
}
#endregion
}
}
| 22.612903 | 115 | 0.546719 | [
"Apache-2.0"
] | bluexray/Horizon.Sample | Horizon.Payment.Alipay/Request/AlipayEbppProdmodeReconconfQueryRequest.cs | 2,822 | C# |
using Firebase.CloudMessaging;
using Rocks.Wasabee.Mobile.Core.Services;
namespace Rocks.Wasabee.Mobile.iOS.Infra.Firebase
{
public class FirebaseService : IFirebaseService
{
public string GetFcmToken()
{
return Messaging.SharedInstance.FcmToken ?? string.Empty;
}
}
} | 24.461538 | 69 | 0.685535 | [
"Apache-2.0"
] | ruharen/Wasabee-Mobile-Xamarin | Rocks.Wasabee.Mobile.iOS/Infra/Firebase/FirebaseService.cs | 320 | C# |
using System;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using EventStore.ClientAPI;
using EventStore.ClientAPI.Common.Log;
using EventStore.ClientAPI.SystemData;
using EventStore.Common.Options;
using EventStore.Core;
using EventStore.Core.Bus;
using EventStore.Core.Tests;
using EventStore.Core.Tests.Helpers;
using EventStore.Projections.Core.Services.Processing;
using NUnit.Framework;
using ResolvedEvent = EventStore.ClientAPI.ResolvedEvent;
namespace EventStore.Projections.Core.Tests.ClientAPI.Cluster
{
[Category("ClientAPI")]
public class specification_with_standard_projections_runnning : SpecificationWithDirectoryPerTestFixture
{
protected MiniClusterNode[] _nodes = new MiniClusterNode[3];
protected Endpoints[] _nodeEndpoints = new Endpoints[3];
protected IEventStoreConnection _conn;
protected ProjectionsSubsystem _projections;
protected UserCredentials _admin = DefaultData.AdminCredentials;
protected ProjectionsManager _manager;
protected class Endpoints
{
public readonly IPEndPoint InternalTcp;
public readonly IPEndPoint InternalTcpSec;
public readonly IPEndPoint InternalHttp;
public readonly IPEndPoint ExternalTcp;
public readonly IPEndPoint ExternalTcpSec;
public readonly IPEndPoint ExternalHttp;
public Endpoints(
int internalTcp, int internalTcpSec, int internalHttp, int externalTcp,
int externalTcpSec, int externalHttp)
{
var testIp = Environment.GetEnvironmentVariable("ES-TESTIP");
var address = string.IsNullOrEmpty(testIp) ? IPAddress.Loopback : IPAddress.Parse(testIp);
InternalTcp = new IPEndPoint(address, internalTcp);
InternalTcpSec = new IPEndPoint(address, internalTcpSec);
InternalHttp = new IPEndPoint(address, internalHttp);
ExternalTcp = new IPEndPoint(address, externalTcp);
ExternalTcpSec = new IPEndPoint(address, externalTcpSec);
ExternalHttp = new IPEndPoint(address, externalHttp);
}
}
[TestFixtureSetUp]
public override void TestFixtureSetUp()
{
base.TestFixtureSetUp();
#if (!DEBUG)
throw new NotSupportedException("These tests require DEBUG conditional");
#else
QueueStatsCollector.InitializeIdleDetection();
_nodeEndpoints[0] = new Endpoints(
PortsHelper.GetAvailablePort(IPAddress.Loopback), PortsHelper.GetAvailablePort(IPAddress.Loopback),
PortsHelper.GetAvailablePort(IPAddress.Loopback), PortsHelper.GetAvailablePort(IPAddress.Loopback),
PortsHelper.GetAvailablePort(IPAddress.Loopback), PortsHelper.GetAvailablePort(IPAddress.Loopback));
_nodeEndpoints[1] = new Endpoints(
PortsHelper.GetAvailablePort(IPAddress.Loopback), PortsHelper.GetAvailablePort(IPAddress.Loopback),
PortsHelper.GetAvailablePort(IPAddress.Loopback), PortsHelper.GetAvailablePort(IPAddress.Loopback),
PortsHelper.GetAvailablePort(IPAddress.Loopback), PortsHelper.GetAvailablePort(IPAddress.Loopback));
_nodeEndpoints[2] = new Endpoints(
PortsHelper.GetAvailablePort(IPAddress.Loopback), PortsHelper.GetAvailablePort(IPAddress.Loopback),
PortsHelper.GetAvailablePort(IPAddress.Loopback), PortsHelper.GetAvailablePort(IPAddress.Loopback),
PortsHelper.GetAvailablePort(IPAddress.Loopback), PortsHelper.GetAvailablePort(IPAddress.Loopback));
PortsHelper.GetAvailablePort(IPAddress.Loopback);
_nodes[0] = CreateNode(0,
_nodeEndpoints[0], new IPEndPoint[] {_nodeEndpoints[1].InternalHttp, _nodeEndpoints[2].InternalHttp});
_nodes[1] = CreateNode(1,
_nodeEndpoints[1], new IPEndPoint[] { _nodeEndpoints[0].InternalHttp, _nodeEndpoints[2].InternalHttp });
_nodes[2] = CreateNode(2,
_nodeEndpoints[2], new IPEndPoint[] { _nodeEndpoints[0].InternalHttp, _nodeEndpoints[1].InternalHttp });
_nodes[0].Start();
_nodes[1].Start();
_nodes[2].Start();
WaitHandle.WaitAll(new[] { _nodes[0].StartedEvent, _nodes[1].StartedEvent, _nodes[2].StartedEvent });
QueueStatsCollector.WaitIdle(waitForNonEmptyTf: true);
_conn = EventStoreConnection.Create(_nodes[0].ExternalTcpEndPoint.ToESTcpUri());
_conn.ConnectAsync().Wait();
_manager = new ProjectionsManager(
new ConsoleLogger(),
_nodes[0].ExternalHttpEndPoint,
TimeSpan.FromMilliseconds(10000));
if (GivenStandardProjectionsRunning())
EnableStandardProjections();
QueueStatsCollector.WaitIdle();
Given();
When();
#endif
}
private MiniClusterNode CreateNode(int index, Endpoints endpoints, IPEndPoint[] gossipSeeds)
{
_projections = new ProjectionsSubsystem(1, runProjections: ProjectionType.All);
var node = new MiniClusterNode(
PathName, index, endpoints.InternalTcp, endpoints.InternalTcpSec, endpoints.InternalHttp, endpoints.ExternalTcp,
endpoints.ExternalTcpSec, endpoints.ExternalHttp, skipInitializeStandardUsersCheck: false,
subsystems: new ISubsystem[] {_projections}, gossipSeeds: gossipSeeds);
WaitIdle();
return node;
}
[TearDown]
public void PostTestAsserts()
{
var all = _manager.ListAllAsync(_admin).Result;
if (all.Contains("Faulted"))
Assert.Fail("Projections faulted while running the test" + "\r\n" + all);
}
protected void EnableStandardProjections()
{
EnableProjection(ProjectionNamesBuilder.StandardProjections.EventByCategoryStandardProjection);
EnableProjection(ProjectionNamesBuilder.StandardProjections.EventByTypeStandardProjection);
EnableProjection(ProjectionNamesBuilder.StandardProjections.StreamByCategoryStandardProjection);
EnableProjection(ProjectionNamesBuilder.StandardProjections.StreamsStandardProjection);
}
protected void DisableStandardProjections()
{
DisableProjection(ProjectionNamesBuilder.StandardProjections.EventByCategoryStandardProjection);
DisableProjection(ProjectionNamesBuilder.StandardProjections.EventByTypeStandardProjection);
DisableProjection(ProjectionNamesBuilder.StandardProjections.StreamByCategoryStandardProjection);
DisableProjection(ProjectionNamesBuilder.StandardProjections.StreamsStandardProjection);
}
protected virtual bool GivenStandardProjectionsRunning()
{
return true;
}
protected void EnableProjection(string name)
{
_manager.EnableAsync(name, _admin).Wait();
}
protected void DisableProjection(string name)
{
_manager.DisableAsync(name, _admin).Wait();
}
[TestFixtureTearDown]
public override void TestFixtureTearDown()
{
_conn.Close();
_nodes[0].Shutdown();
_nodes[1].Shutdown();
_nodes[2].Shutdown();
base.TestFixtureTearDown();
#if DEBUG
QueueStatsCollector.InitializeIdleDetection(false);
#endif
}
protected virtual void When()
{
}
protected virtual void Given()
{
}
protected void PostEvent(string stream, string eventType, string data)
{
_conn.AppendToStreamAsync(stream, ExpectedVersion.Any, new[] {CreateEvent(eventType, data)}).Wait();
}
protected void HardDeleteStream(string stream)
{
_conn.DeleteStreamAsync(stream, ExpectedVersion.Any, true, _admin).Wait();
}
protected void SoftDeleteStream(string stream)
{
_conn.DeleteStreamAsync(stream, ExpectedVersion.Any, false, _admin).Wait();
}
protected static EventData CreateEvent(string type, string data)
{
return new EventData(Guid.NewGuid(), type, true, Encoding.UTF8.GetBytes(data), new byte[0]);
}
protected static void WaitIdle()
{
QueueStatsCollector.WaitIdle();
}
[Conditional("DEBUG")]
protected void AssertStreamTail(string streamId, params string[] events)
{
#if DEBUG
var result = _conn.ReadStreamEventsBackwardAsync(streamId, -1, events.Length, true, _admin).Result;
switch (result.Status)
{
case SliceReadStatus.StreamDeleted:
Assert.Fail("Stream '{0}' is deleted", streamId);
break;
case SliceReadStatus.StreamNotFound:
Assert.Fail("Stream '{0}' does not exist", streamId);
break;
case SliceReadStatus.Success:
var resultEventsReversed = result.Events.Reverse().ToArray();
if (resultEventsReversed.Length < events.Length)
DumpFailed("Stream does not contain enough events", streamId, events, result.Events);
else
{
for (var index = 0; index < events.Length; index++)
{
var parts = events[index].Split(new char[] { ':' }, 2);
var eventType = parts[0];
var eventData = parts[1];
if (resultEventsReversed[index].Event.EventType != eventType)
DumpFailed("Invalid event type", streamId, events, resultEventsReversed);
else
if (resultEventsReversed[index].Event.DebugDataView != eventData)
DumpFailed("Invalid event body", streamId, events, resultEventsReversed);
}
}
break;
}
#endif
}
[Conditional("DEBUG")]
protected void DumpStream(string streamId)
{
#if DEBUG
var result = _conn.ReadStreamEventsBackwardAsync(streamId, -1, 100, true, _admin).Result;
switch (result.Status)
{
case SliceReadStatus.StreamDeleted:
Assert.Fail("Stream '{0}' is deleted", streamId);
break;
case SliceReadStatus.StreamNotFound:
Assert.Fail("Stream '{0}' does not exist", streamId);
break;
case SliceReadStatus.Success:
Dump("Dumping..", streamId, result.Events.Reverse().ToArray());
break;
}
#endif
}
#if DEBUG
private void DumpFailed(string message, string streamId, string[] events, ResolvedEvent[] resultEvents)
{
var expected = events.Aggregate("", (a, v) => a + ", " + v);
var actual = resultEvents.Aggregate(
"", (a, v) => a + ", " + v.Event.EventType + ":" + v.Event.DebugDataView);
var actualMeta = resultEvents.Aggregate(
"", (a, v) => a + "\r\n" + v.Event.EventType + ":" + v.Event.DebugMetadataView);
Assert.Fail(
"Stream: '{0}'\r\n{1}\r\n\r\nExisting events: \r\n{2}\r\n Expected events: \r\n{3}\r\n\r\nActual metas:{4}", streamId,
message, actual, expected, actualMeta);
}
private void Dump(string message, string streamId, ResolvedEvent[] resultEvents)
{
var actual = resultEvents.Aggregate(
"", (a, v) => a + ", " + v.OriginalEvent.EventType + ":" + v.OriginalEvent.DebugDataView);
var actualMeta = resultEvents.Aggregate(
"", (a, v) => a + "\r\n" + v.OriginalEvent.EventType + ":" + v.OriginalEvent.DebugMetadataView);
Debug.WriteLine(
"Stream: '{0}'\r\n{1}\r\n\r\nExisting events: \r\n{2}\r\n \r\nActual metas:{3}", streamId,
message, actual, actualMeta);
}
#endif
protected void PostProjection(string query)
{
_manager.CreateContinuousAsync("test-projection", query, _admin).Wait();
WaitIdle();
}
}
[TestFixture, Explicit]
public class TestTest : specification_with_standard_projections_runnning
{
[Test, Explicit]
public void Test()
{
PostProjection(@"fromStream('$user-admin').outputState()");
AssertStreamTail("$projections-test-projection-result", "Result:{}");
}
}
}
| 41.700637 | 134 | 0.613258 | [
"Apache-2.0"
] | betgenius/EventStore | src/EventStore.Projections.Core.Tests/ClientAPI/Cluster/specification_with_standard_projections_runnning.cs | 13,096 | C# |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using Shouldly;
using System.Collections.Generic;
using System.Text.Json;
using Yuniql.Core;
using Yuniql.Extensibility;
namespace Yuniql.UnitTests
{
[TestClass]
public class ConfigurationServiceTests: TestClassBase
{
private Configuration GetFreshConfiguration()
{
var configuration = Configuration.Instance;
configuration.Workspace = @"c:\temp\yuniql";
configuration.IsDebug = true;
configuration.Platform = SUPPORTED_DATABASES.SQLSERVER;
configuration.ConnectionString = "sqlserver-connectionstring";
configuration.CommandTimeout = 30;
configuration.TargetVersion = "v0.00";
configuration.IsAutoCreateDatabase = true;
configuration.Tokens = new List<KeyValuePair<string, string>> {
new KeyValuePair<string, string> ("token1", "value1"),
new KeyValuePair<string, string> ("token2", "value2"),
new KeyValuePair<string, string> ("token3", "value3")
};
configuration.BulkSeparator = ";";
configuration.BulkBatchSize = 1000;
configuration.Environment = "dev";
configuration.MetaSchemaName = "yuniql_schema";
configuration.MetaTableName = "yuniql_table";
configuration.TransactionMode = TRANSACTION_MODE.SESSION;
configuration.IsContinueAfterFailure = true;
configuration.IsRequiredClearedDraft = true;
configuration.IsForced = true;
configuration.IsVerifyOnly = true;
configuration.AppliedByTool = "yuniql-cli";
configuration.AppliedByToolVersion = "1.0.0.0";
return configuration;
}
[TestMethod]
public void Test_Paremeters_Mapped_To_Configuration()
{
//arrange
var traceService = new Mock<ITraceService>();
var workspaceService = new Mock<IWorkspaceService>();
var parameters = GetFreshConfiguration();
var environmentService = new Mock<IEnvironmentService>();
environmentService.Setup(s => s.GetEnvironmentVariable(ENVIRONMENT_VARIABLE.YUNIQL_WORKSPACE)).Returns(parameters.Workspace);
environmentService.Setup(s => s.GetEnvironmentVariable(ENVIRONMENT_VARIABLE.YUNIQL_PLATFORM)).Returns(parameters.Platform);
environmentService.Setup(s => s.GetEnvironmentVariable(ENVIRONMENT_VARIABLE.YUNIQL_CONNECTION_STRING)).Returns(parameters.ConnectionString);
//act
var sut = new ConfigurationService(environmentService.Object, workspaceService.Object, traceService.Object);
sut.Initialize();
var configuration = sut.GetConfiguration();
//assert
var parameterJson = JsonSerializer.Serialize(parameters, new JsonSerializerOptions { WriteIndented = true, IgnoreReadOnlyProperties = true, PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
var configurationJson = JsonSerializer.Serialize(configuration, new JsonSerializerOptions { WriteIndented = true, IgnoreReadOnlyProperties = true, PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
parameterJson.ShouldBe(configurationJson);
}
[TestMethod]
public void Test_Trace_Sensitive_Data_Disabled()
{
//arrange
var traceService = new Mock<ITraceService>();
var workspaceService = new Mock<IWorkspaceService>();
var parameters = GetFreshConfiguration();
var environmentService = new Mock<IEnvironmentService>();
environmentService.Setup(s => s.GetEnvironmentVariable(ENVIRONMENT_VARIABLE.YUNIQL_WORKSPACE)).Returns(parameters.Workspace);
environmentService.Setup(s => s.GetEnvironmentVariable(ENVIRONMENT_VARIABLE.YUNIQL_PLATFORM)).Returns(parameters.Platform);
environmentService.Setup(s => s.GetEnvironmentVariable(ENVIRONMENT_VARIABLE.YUNIQL_CONNECTION_STRING)).Returns(parameters.ConnectionString);
//act
var sut = new ConfigurationService(environmentService.Object, workspaceService.Object, traceService.Object);
sut.Initialize();
var configurationJson = sut.PrintAsJson();
//assert
var configuration = JsonSerializer.Deserialize<Configuration>(configurationJson, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
configuration.ConnectionString.ShouldBe("<sensitive-data-redacted>");
}
[TestMethod]
public void Test_Trace_Sensitive_Data_Enabled()
{
//arrange
var traceService = new Mock<ITraceService>();
var workspaceService = new Mock<IWorkspaceService>();
traceService.Setup(property => property.IsTraceSensitiveData).Returns(true); //Enable TraceSensitiveData for the current test
var parameters = GetFreshConfiguration();
var environmentService = new Mock<IEnvironmentService>();
environmentService.Setup(s => s.GetEnvironmentVariable(ENVIRONMENT_VARIABLE.YUNIQL_WORKSPACE)).Returns(parameters.Workspace);
environmentService.Setup(s => s.GetEnvironmentVariable(ENVIRONMENT_VARIABLE.YUNIQL_PLATFORM)).Returns(parameters.Platform);
environmentService.Setup(s => s.GetEnvironmentVariable(ENVIRONMENT_VARIABLE.YUNIQL_CONNECTION_STRING)).Returns(parameters.ConnectionString);
//act
var sut = new ConfigurationService(environmentService.Object, workspaceService.Object, traceService.Object);
sut.Initialize();
var configurationJson = sut.PrintAsJson();
//assert
var configuration = JsonSerializer.Deserialize<Configuration>(configurationJson, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
configuration.ConnectionString.ShouldBe(parameters.ConnectionString);
}
[TestMethod]
public void Test_GetValueOrDefault_With_Use_Original_Value()
{
//arrange
var traceService = new Mock<ITraceService>();
var environmentService = new Mock<IEnvironmentService>();
var workspaceService = new Mock<IWorkspaceService>();
//act
var sut = new ConfigurationService(environmentService.Object, workspaceService.Object, traceService.Object);
var result = sut.GetValueOrDefault("mariadb", ENVIRONMENT_VARIABLE.YUNIQL_PLATFORM, SUPPORTED_DATABASES.SQLSERVER);
//assert
result.ShouldBe("mariadb");
}
[TestMethod]
public void Test_GetValueOrDefault_Use_Environment_Variable()
{
//arrange
var traceService = new Mock<ITraceService>();
var environmentService = new Mock<IEnvironmentService>();
environmentService.Setup(s => s.GetEnvironmentVariable(ENVIRONMENT_VARIABLE.YUNIQL_PLATFORM)).Returns(SUPPORTED_DATABASES.MARIADB);
var workspaceService = new Mock<IWorkspaceService>();
//act
var sut = new ConfigurationService(environmentService.Object, workspaceService.Object, traceService.Object);
var result = sut.GetValueOrDefault(null, ENVIRONMENT_VARIABLE.YUNIQL_PLATFORM, SUPPORTED_DATABASES.SQLSERVER);
//assert
result.ShouldBe(SUPPORTED_DATABASES.MARIADB);
}
[TestMethod]
public void Test_GetValueOrDefault_Use_Default_Value()
{
//arrange
var traceService = new Mock<ITraceService>();
var environmentService = new Mock<IEnvironmentService>();
var workspaceService = new Mock<IWorkspaceService>();
//act
var sut = new ConfigurationService(environmentService.Object, workspaceService.Object, traceService.Object);
var result = sut.GetValueOrDefault(null, ENVIRONMENT_VARIABLE.YUNIQL_PLATFORM, SUPPORTED_DATABASES.SQLSERVER);
//assert
result.ShouldBe(SUPPORTED_DATABASES.SQLSERVER);
}
}
}
| 48.158824 | 212 | 0.678759 | [
"Apache-2.0"
] | automada/yuniql | yuniql-tests/unit-tests/Tests/ConfigurationServiceTests.cs | 8,189 | C# |
namespace SubterfugeCore.Core.Network
{
public class SubmitEventResponse : BaseNetworkResponse
{
public int RoomId { get; set; }
}
} | 21.857143 | 58 | 0.679739 | [
"CC0-1.0"
] | LordSputnik/Remake-Core | SubterfugeCore/Core/Network/ResponseModels/SubmitEventResponse.cs | 155 | 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("DateDifference")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DateDifference")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("1f393b29-a487-4875-b2d9-01aac91a3aba")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.864865 | 84 | 0.745896 | [
"MIT"
] | VProfirov/Telerik-Academy | Module 1/[02] CSharp Advanced/[performance improvement versions] C# Advanced/C# Advanced v0.1/Strings-And-Text-Processing/DateDifference/Properties/AssemblyInfo.cs | 1,404 | C# |
using Gsemac.IO;
using Gsemac.IO.Extensions;
using Gsemac.Reflection.Plugins;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Gsemac.Drawing.Imaging {
public class ImageCodecFactory :
IImageCodecFactory {
// Public members
public static ImageCodecFactory Default => new ImageCodecFactory();
public ImageCodecFactory() :
this(null) {
}
public ImageCodecFactory(IPluginLoader pluginLoader) {
if (pluginLoader is null)
this.pluginLoader = new Lazy<IPluginLoader>(CreateDefaultPluginLoader);
else
this.pluginLoader = new Lazy<IPluginLoader>(() => pluginLoader);
}
public IEnumerable<IFileFormat> GetSupportedFileFormats() {
return GetSupportedImageFormats();
}
public IImageCodec FromFileFormat(IFileFormat imageFormat) {
return GetImageCodecs(imageFormat).FirstOrDefault(codec => codec.IsSupportedFileFormat(imageFormat));
}
// Private members
private readonly Lazy<IPluginLoader> pluginLoader;
private IPluginLoader CreateDefaultPluginLoader() {
return new PluginLoader<IImageCodec>(new PluginLoaderOptions() {
PluginSearchPattern = "Gsemac.Drawing.Imaging.*.dll",
});
}
private IEnumerable<IImageCodec> GetImageCodecs() {
return GetImageCodecs(null);
}
private IEnumerable<IFileFormat> GetSupportedImageFormats() {
return GetImageCodecs().SelectMany(codec => codec.GetSupportedFileFormats())
.Distinct()
.OrderBy(type => type);
}
private IEnumerable<IImageCodec> GetImageCodecs(IFileFormat imageFormat) {
List<IImageCodec> imageCodecs = new List<IImageCodec>();
foreach (IImageCodec imageCodec in pluginLoader.Value.GetPlugins<IImageCodec>()) {
IImageCodec nextImageCodec = imageCodec;
Type nextImageCodecType = imageCodec.GetType();
if (!(nextImageCodec is null) && !(imageFormat is null) && nextImageCodec.IsSupportedFileFormat(imageFormat) && nextImageCodecType.GetConstructor(new[] { typeof(IFileFormat) }) != null)
nextImageCodec = (IImageCodec)Activator.CreateInstance(nextImageCodecType, new object[] { imageFormat });
imageCodecs.Add(nextImageCodec);
}
return imageCodecs;
}
}
} | 29.569767 | 201 | 0.638616 | [
"MIT"
] | gsemac/Gsemac.Common | src/Gsemac.Drawing/Imaging/ImageCodecFactory.cs | 2,545 | C# |
using System.CommandLine;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using EMG.Tools.EnsureUnique;
using EMG.Tools.EnsureUnique.Concurrency;
using EMG.Tools.EnsureUnique.TokenGenerators;
using NUnit.Framework;
namespace Tests
{
[TestFixture]
[TestOf(typeof(RunDotNetCommand))]
public class RunDotNetCommandTests
{
[Test, CustomAutoData]
public void Constructor_adds_Path_argument(RunDotNetCommand sut)
{
Assert.That(sut.Arguments, Has.Exactly(1).InstanceOf<Argument<FileInfo>>().With.Property(nameof(Argument.Name)).EqualTo(nameof(RunCommandArguments.PathToProgram)));
}
[Test]
[InlineCustomAutoData(nameof(S3ConcurrencyServiceOptions.BucketName))]
[InlineCustomAutoData(nameof(S3ConcurrencyServiceOptions.FilePrefix))]
[InlineCustomAutoData(nameof(TokenOptions.Token))]
[InlineCustomAutoData(nameof(RunCommandArguments.ProgramArguments))]
public void Constructor_adds_options(string optionName, RunDotNetCommand sut)
{
Assert.That(sut.Options, Has.Exactly(1).InstanceOf<Option<string>>().With.Property(nameof(Option.Name)).EqualTo(optionName));
}
[Test]
[CustomAutoData]
public async Task Bucket_option_is_correctly_parsed(RunDotNetCommand sut, CommandHandlerSpy commandHandler, string program, string bucket)
{
sut.Handler = commandHandler;
await sut.InvokeAsync($"dotnet {program} --bucket {bucket}");
Assert.That(commandHandler.InvocationContext.ParseResult.ValueForOption(CommonOptions.BucketNameOption), Is.EqualTo(bucket));
}
[Test]
[CustomAutoData]
public async Task FilePrefix_option_is_correctly_parsed(RunDotNetCommand sut, CommandHandlerSpy commandHandler, string program, string filePrefix)
{
sut.Handler = commandHandler;
await sut.InvokeAsync($"dotnet {program} --prefix {filePrefix}");
Assert.That(commandHandler.InvocationContext.ParseResult.ValueForOption(CommonOptions.FilePrefixOption), Is.EqualTo(filePrefix));
}
[Test]
[CustomAutoData]
public async Task Token_option_is_correctly_parsed_when_added(RunDotNetCommand sut, CommandHandlerSpy commandHandler, string program, string token)
{
sut.Handler = commandHandler;
await sut.InvokeAsync($"dotnet {program} --token {token}");
Assert.That(commandHandler.InvocationContext.ParseResult.ValueForOption(CommonOptions.TokenOption), Is.EqualTo(token));
}
[Test]
[CustomAutoData]
public async Task Token_option_is_null_when_not_added(RunDotNetCommand sut, CommandHandlerSpy commandHandler, string program)
{
sut.Handler = commandHandler;
await sut.InvokeAsync($"dotnet {program}");
Assert.That(commandHandler.InvocationContext.ParseResult.ValueForOption(CommonOptions.TokenOption), Is.Null);
}
[Test]
[CustomAutoData]
public async Task PathToProgram_is_correctly_parsed(RunDotNetCommand sut, CommandHandlerSpy commandHandler, string program)
{
sut.Handler = commandHandler;
await sut.InvokeAsync($"dotnet {program}");
Assert.That(commandHandler.InvocationContext.ParseResult.ValueForArgument(sut.Arguments.First() as Argument<FileInfo>).ToString(), Is.EqualTo(program));
}
}
} | 39.784091 | 176 | 0.702942 | [
"MIT"
] | annasandberg/dotnet-ensure-unique | tests/Tests.EnsureUnique/RunDotNetCommandTests.cs | 3,501 | C# |
using System;
using System.Reflection;
using System.Threading.Tasks;
using Discord;
using Discord.WebSocket;
namespace Bot_Boi
{
class Program
{
DiscordSocketClient _client;
CommandHandler _handler;
static void Main(string[] args)
=> new Program().StartAsync().GetAwaiter().GetResult();
public async Task StartAsync()
{
if (Config.bot.token == "" || Config.bot.token == null) return;
_client = new DiscordSocketClient(new DiscordSocketConfig
{
LogLevel = LogSeverity.Verbose
});
_client.Log += Log;
await _client.LoginAsync(TokenType.Bot, Config.bot.token);
await _client.StartAsync();
_handler = new CommandHandler();
await _handler.InitializeAsync(_client);
await Task.Delay(-1);
}
private async Task Log(LogMessage msg)
{
Console.WriteLine(msg.Source + " " + msg.Message);
}
private readonly Assembly _assembly = Assembly.GetExecutingAssembly();
}
} | 27.219512 | 78 | 0.587814 | [
"MIT"
] | aeonian13/Discord.Net-Bot-Code-Base | Program.cs | 1,118 | C# |
/*
* Copyright 2012-2019 The Pkcs11Interop Project
*
* 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.
*/
/*
* Written for the Pkcs11Interop project by:
* Jaroslav IMRICH <jimrich@jimrich.sk>
*/
using System;
using Net.Pkcs11Interop.Common;
using Net.Pkcs11Interop.LowLevelAPI81;
using NUnit.Framework;
using NativeULong = System.UInt64;
// Note: Code in this file is generated automatically.
namespace Net.Pkcs11Interop.Tests.LowLevelAPI81
{
/// <summary>
/// C_GetOperationState and C_SetOperationState tests.
/// </summary>
[TestFixture()]
public class _07_OperationStateTest
{
/// <summary>
/// Basic C_GetOperationState and C_SetOperationState test.
/// </summary>
[Test()]
public void _01_BasicOperationStateTest()
{
Helpers.CheckPlatform();
CKR rv = CKR.CKR_OK;
using (Pkcs11Library pkcs11Library = new Pkcs11Library(Settings.Pkcs11LibraryPath))
{
rv = pkcs11Library.C_Initialize(Settings.InitArgs81);
if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED))
Assert.Fail(rv.ToString());
// Find first slot with token present
NativeULong slotId = Helpers.GetUsableSlot(pkcs11Library);
// Open RO (read-only) session
NativeULong session = CK.CK_INVALID_HANDLE;
rv = pkcs11Library.C_OpenSession(slotId, CKF.CKF_SERIAL_SESSION, IntPtr.Zero, IntPtr.Zero, ref session);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Get length of state in first call
NativeULong stateLen = 0;
rv = pkcs11Library.C_GetOperationState(session, null, ref stateLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
Assert.IsTrue(stateLen > 0);
// Allocate array for state
byte[] state = new byte[stateLen];
// Get state in second call
rv = pkcs11Library.C_GetOperationState(session, state, ref stateLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Let's set state so the test is complete
rv = pkcs11Library.C_SetOperationState(session, state, ConvertUtils.UInt64FromInt32(state.Length), CK.CK_INVALID_HANDLE, CK.CK_INVALID_HANDLE);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11Library.C_CloseSession(session);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11Library.C_Finalize(IntPtr.Zero);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
}
}
}
}
| 36.520833 | 159 | 0.583286 | [
"Apache-2.0"
] | uae1972/Pkcs11Interop | src/Pkcs11Interop.Tests/LowLevelAPI81/_07_OperationStateTest.cs | 3,506 | C# |
using Microsoft.ML;
using System.Threading.Tasks;
using Watchster.Application.Utils.ML.Models;
namespace Watchster.Application.Utils.ML
{
public interface IMLModelBuilder
{
Task<PredictionEngine<MovieRating, MovieRatingPrediction>> ConstructMoviePredictModelAsync();
}
} | 26.545455 | 101 | 0.780822 | [
"MIT"
] | iulianPeiu6/Watchster | WatchsterSolution/Watchster.Application/Utils/ML/Interfaces/IMLModelBuilder.cs | 294 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="CacheStorage.cs" company="Catel development team">
// Copyright (c) 2008 - 2015 Catel development team. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Catel.Caching
{
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading.Tasks;
using Policies;
using Threading;
/// <summary>
/// The cache storage.
/// </summary>
/// <typeparam name="TKey">The key type.</typeparam>
/// <typeparam name="TValue">The value type.</typeparam>
public class CacheStorage<TKey, TValue> : ICacheStorage<TKey, TValue>
{
#region Fields
private readonly Func<ExpirationPolicy> _defaultExpirationPolicyInitCode;
/// <summary>
/// Determines whether the cache storage can store null values.
/// </summary>
private readonly bool _storeNullValues;
/// <summary>
/// The dictionary.
/// </summary>
private readonly Dictionary<TKey, CacheStorageValueInfo<TValue>> _dictionary;
/// <summary>
/// The synchronization object.
/// </summary>
private readonly object _syncObj = new object();
/// <summary>
/// The async locks.
/// </summary>
private readonly Dictionary<TKey, AsyncLock> _locksByKey = new Dictionary<TKey, AsyncLock>();
/// <summary>
/// The lock used when the key is <c>null</c>.
/// </summary>
private readonly AsyncLock _nullKeyLock = new AsyncLock();
/// <summary>
/// The timer that is being executed to invalidate the cache.
/// </summary>
private Catel.Threading.Timer _expirationTimer;
/// <summary>
/// The expiration timer interval.
/// </summary>
private TimeSpan _expirationTimerInterval;
/// <summary>
/// Determines whether the cache storage can check for expired items.
/// </summary>
private bool _checkForExpiredItems;
#endregion
/// <summary>
/// Occurs when the item is expiring.
/// </summary>
public event EventHandler<ExpiringEventArgs<TKey, TValue>> Expiring;
/// <summary>
/// Occurs when the item has expired.
/// </summary>
public event EventHandler<ExpiredEventArgs<TKey, TValue>> Expired;
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="CacheStorage{TKey,TValue}" /> class.
/// </summary>
/// <param name="defaultExpirationPolicyInitCode">The default expiration policy initialization code.</param>
/// <param name="storeNullValues">Allow store null values on the cache.</param>
/// <param name="equalityComparer">The equality comparer.</param>
public CacheStorage(Func<ExpirationPolicy> defaultExpirationPolicyInitCode = null, bool storeNullValues = false,
IEqualityComparer<TKey> equalityComparer = null)
{
_dictionary = new Dictionary<TKey, CacheStorageValueInfo<TValue>>(equalityComparer);
_storeNullValues = storeNullValues;
_defaultExpirationPolicyInitCode = defaultExpirationPolicyInitCode;
_expirationTimerInterval = TimeSpan.FromSeconds(1);
}
#endregion
#region ICacheStorage<TKey,TValue> Members
/// <summary>
/// Gets or sets whether values should be disposed on removal.
/// </summary>
/// <value><c>true</c> if values should be disposed on removal; otherwise, <c>false</c>.</value>
public bool DisposeValuesOnRemoval { get; set; }
/// <summary>
/// Gets the value associated with the specified key.
/// </summary>
/// <param name="key">The key.</param>
/// <returns>The value associated with the specified key, or default value for the type of the value if the key do not exists.</returns>
/// <exception cref="ArgumentNullException">The <paramref name="key" /> is <c>null</c>.</exception>
public TValue this[TKey key]
{
get { return Get(key); }
}
/// <summary>
/// Gets the keys so it is possible to enumerate the cache.
/// </summary>
/// <value>The keys.</value>
public IEnumerable<TKey> Keys
{
get
{
lock (_syncObj)
{
return _dictionary.Keys;
}
}
}
/// <summary>
/// Gets or sets the expiration timer interval.
/// <para />
/// The default value is <c>TimeSpan.FromSeconds(1)</c>.
/// </summary>
/// <value>The expiration timer interval.</value>
public TimeSpan ExpirationTimerInterval
{
get { return _expirationTimerInterval; }
set
{
_expirationTimerInterval = value;
UpdateTimer();
}
}
private void UpdateTimer()
{
lock (_syncObj)
{
if (!_checkForExpiredItems)
{
if (_expirationTimer != null)
{
_expirationTimer.Dispose();
_expirationTimer = null;
}
}
else
{
var timeSpan = _expirationTimerInterval;
if (_expirationTimer is null)
{
// Always create timers with infinite, then update them later so we always have a populated timer field
_expirationTimer = new Catel.Threading.Timer(OnTimerElapsed, null, Timeout.Infinite, Timeout.Infinite);
}
_expirationTimer.Change(timeSpan, timeSpan);
}
}
}
/// <summary>
/// Gets the value associated with the specified key
/// </summary>
/// <param name="key">The key of the value to get.</param>
/// <returns>The value associated with the specified key, or default value for the type of the value if the key do not exists.</returns>
/// <exception cref="ArgumentNullException">The <paramref name="key" /> is <c>null</c>.</exception>
public TValue Get(TKey key)
{
Argument.IsNotNull("key", key);
return ExecuteInLock(key, () =>
{
_dictionary.TryGetValue(key, out var valueInfo);
return (valueInfo != null) ? valueInfo.Value : default(TValue);
});
}
/// <summary>
/// Determines whether the cache contains a value associated with the specified key.
/// </summary>
/// <param name="key">The key.</param>
/// <returns><c>true</c> if the cache contains an element with the specified key; otherwise, <c>false</c>.</returns>
/// <exception cref="ArgumentNullException">The <paramref name="key" /> is <c>null</c>.</exception>
public bool Contains(TKey key)
{
Argument.IsNotNull("key", key);
return ExecuteInLock(key, () =>
{
return _dictionary.ContainsKey(key);
});
}
/// <summary>
/// Adds a value to the cache associated with to a key.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="code">The deferred initialization code of the value.</param>
/// <param name="expirationPolicy">The expiration policy.</param>
/// <param name="override">Indicates if the key exists the value will be overridden.</param>
/// <returns>The instance initialized by the <paramref name="code" />.</returns>
/// <exception cref="ArgumentNullException">If <paramref name="key" /> is <c>null</c>.</exception>
/// <exception cref="ArgumentNullException">If <paramref name="code" /> is <c>null</c>.</exception>
[SuppressMessage("StyleCop.CSharp.SpacingRules", "SA1027:TabsMustNotBeUsed", Justification = "Reviewed. Suppression is OK here.")]
public TValue GetFromCacheOrFetch(TKey key, Func<TValue> code, ExpirationPolicy expirationPolicy, bool @override = false)
{
Argument.IsNotNull("key", key);
Argument.IsNotNull("code", code);
return ExecuteInLock(key, () =>
{
if (!@override && _dictionary.TryGetValue(key, out var cacheStorageValueInfo))
{
return cacheStorageValueInfo.Value;
}
var value = code();
if (!ReferenceEquals(value, null) || _storeNullValues)
{
if (expirationPolicy is null && _defaultExpirationPolicyInitCode != null)
{
expirationPolicy = _defaultExpirationPolicyInitCode();
}
var valueInfo = new CacheStorageValueInfo<TValue>(value, expirationPolicy);
lock (_syncObj)
{
_dictionary[key] = valueInfo;
}
if (valueInfo.CanExpire)
{
_checkForExpiredItems = true;
}
if (expirationPolicy != null && _expirationTimer is null)
{
UpdateTimer();
}
}
return value;
});
}
/// <summary>
/// Adds a value to the cache associated with to a key.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="code">The deferred initialization code of the value.</param>
/// <param name="override">Indicates if the key exists the value will be overridden.</param>
/// <param name="expiration">The timespan in which the cache item should expire when added.</param>
/// <returns>The instance initialized by the <paramref name="code" />.</returns>
/// <exception cref="ArgumentNullException">If <paramref name="key" /> is <c>null</c>.</exception>
/// <exception cref="ArgumentNullException">If <paramref name="code" /> is <c>null</c>.</exception>
public TValue GetFromCacheOrFetch(TKey key, Func<TValue> code, bool @override = false, TimeSpan expiration = default(TimeSpan))
{
return GetFromCacheOrFetch(key, code, ExpirationPolicy.Duration(expiration), @override);
}
/// <summary>
/// Adds a value to the cache associated with to a key asynchronously.
/// <para />
/// Note that this is a wrapper around <see cref="GetFromCacheOrFetch(TKey,System.Func{TValue},ExpirationPolicy,bool)"/>.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="code">The deferred initialization code of the value.</param>
/// <param name="expirationPolicy">The expiration policy.</param>
/// <param name="override">Indicates if the key exists the value will be overridden.</param>
/// <returns>The instance initialized by the <paramref name="code" />.</returns>
/// <exception cref="ArgumentNullException">If <paramref name="key" /> is <c>null</c>.</exception>
/// <exception cref="ArgumentNullException">If <paramref name="code" /> is <c>null</c>.</exception>
public Task<TValue> GetFromCacheOrFetchAsync(TKey key, Func<Task<TValue>> code, ExpirationPolicy expirationPolicy, bool @override = false)
{
Argument.IsNotNull("key", key);
Argument.IsNotNull("code", code);
return ExecuteInLockAsync(key, async () =>
{
if (!@override && _dictionary.TryGetValue(key, out var cacheStorageValueInfo))
{
return cacheStorageValueInfo.Value;
}
var value = await code();
if (!ReferenceEquals(value, null) || _storeNullValues)
{
if (expirationPolicy is null && _defaultExpirationPolicyInitCode != null)
{
expirationPolicy = _defaultExpirationPolicyInitCode();
}
var valueInfo = new CacheStorageValueInfo<TValue>(value, expirationPolicy);
lock (_syncObj)
{
_dictionary[key] = valueInfo;
}
if (valueInfo.CanExpire)
{
_checkForExpiredItems = true;
}
if (expirationPolicy != null && _expirationTimer is null)
{
UpdateTimer();
}
}
return value;
});
}
/// <summary>
/// Adds a value to the cache associated with to a key asynchronously.
/// <para />
/// Note that this is a wrapper around <see cref="GetFromCacheOrFetch(TKey,System.Func{TValue},bool,TimeSpan)"/>.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="code">The deferred initialization code of the value.</param>
/// <param name="override">Indicates if the key exists the value will be overridden.</param>
/// <param name="expiration">The timespan in which the cache item should expire when added.</param>
/// <returns>The instance initialized by the <paramref name="code" />.</returns>
/// <exception cref="ArgumentNullException">If <paramref name="key" /> is <c>null</c>.</exception>
/// <exception cref="ArgumentNullException">If <paramref name="code" /> is <c>null</c>.</exception>
public Task<TValue> GetFromCacheOrFetchAsync(TKey key, Func<Task<TValue>> code, bool @override = false, TimeSpan expiration = default(TimeSpan))
{
return GetFromCacheOrFetchAsync(key, code, ExpirationPolicy.Duration(expiration), @override);
}
/// <summary>
/// Adds a value to the cache associated with to a key.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <param name="override">Indicates if the key exists the value will be overridden.</param>
/// <param name="expiration">The timespan in which the cache item should expire when added.</param>
/// <exception cref="ArgumentNullException">The <paramref name="key" /> is <c>null</c>.</exception>
public void Add(TKey key, TValue @value, bool @override = false, TimeSpan expiration = default(TimeSpan))
{
Add(key, value, ExpirationPolicy.Duration(expiration), @override);
}
/// <summary>
/// Adds a value to the cache associated with to a key.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <param name="expirationPolicy">The expiration policy.</param>
/// <param name="override">Indicates if the key exists the value will be overridden.</param>
/// <exception cref="ArgumentNullException">The <paramref name="key" /> is <c>null</c>.</exception>
public void Add(TKey key, TValue @value, ExpirationPolicy expirationPolicy, bool @override = false)
{
Argument.IsNotNull("key", key);
if (!_storeNullValues)
{
Argument.IsNotNull("value", value);
}
GetFromCacheOrFetch(key, () => @value, expirationPolicy, @override);
}
/// <summary>
/// Removes an item from the cache.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="action">The action that need to be executed in synchronization with the item cache removal.</param>
/// <exception cref="ArgumentNullException">The <paramref name="key" /> is <c>null</c>.</exception>
public void Remove(TKey key, Action action = null)
{
Argument.IsNotNull("key", key);
ExecuteInLock(key, () =>
{
RemoveItem(key, false, action);
});
}
/// <summary>
/// Clears all the items currently in the cache.
/// </summary>
public void Clear()
{
var keysToRemove = new List<TKey>();
lock (_syncObj)
{
keysToRemove.AddRange(_dictionary.Keys);
foreach (var keyToRemove in keysToRemove)
{
ExecuteInLock(keyToRemove, () =>
{
RemoveItem(keyToRemove, false);
});
}
_checkForExpiredItems = false;
UpdateTimer();
}
}
/// <summary>
/// Removes the expired items from the cache.
/// </summary>
[SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1409:RemoveUnnecessaryCode", Justification = "Reviewed. Suppression is OK here.")]
private void RemoveExpiredItems()
{
var containsItemsThatCanExpire = false;
var keysToRemove = new List<TKey>();
lock (_syncObj)
{
foreach (var cacheItem in _dictionary)
{
var valueInfo = cacheItem.Value;
if (valueInfo.IsExpired)
{
keysToRemove.Add(cacheItem.Key);
}
else
{
if (!containsItemsThatCanExpire && valueInfo.CanExpire)
{
containsItemsThatCanExpire = true;
}
}
}
}
foreach (var keyToRemove in keysToRemove)
{
ExecuteInLock(keyToRemove, () =>
{
var removed = RemoveItem(keyToRemove, true);
if (!removed && !containsItemsThatCanExpire && _dictionary[keyToRemove].CanExpire)
{
containsItemsThatCanExpire = true;
}
});
}
lock (_syncObj)
{
if (_checkForExpiredItems != containsItemsThatCanExpire)
{
_checkForExpiredItems = containsItemsThatCanExpire;
UpdateTimer();
}
}
}
private void ExecuteInLock(TKey key, Action action)
{
ExecuteInLock(key, () =>
{
action();
return true;
});
}
private T ExecuteInLock<T>(TKey key, Func<T> action)
{
// Note: check comments below, this lock is required like this
var asyncLock = GetLockByKey(key);
lock (asyncLock)
{
// Looks complex, but we need to ensure that we can enter the same lock multiple times in non-async scenarios
var taken = asyncLock.IsTaken;
IDisposable unlockDisposable = null;
try
{
if (!taken)
{
unlockDisposable = asyncLock.Lock();
}
return action();
}
finally
{
unlockDisposable?.Dispose();
}
}
}
private Task ExecuteInLockAsync(TKey key, Func<Task> action)
{
return ExecuteInLockAsync(key, async () =>
{
await action();
return true;
});
}
private async Task<T> ExecuteInLockAsync<T>(TKey key, Func<Task<T>> action)
{
var asyncLock = GetLockByKey(key);
using (await asyncLock.LockAsync())
{
return await action();
}
}
/// <summary>
/// Gets the lock by key.
/// </summary>
/// <param name="key">The key.</param>
/// <returns>The lock object.</returns>
private AsyncLock GetLockByKey(TKey key)
{
if (ReferenceEquals(null, key))
{
return _nullKeyLock;
}
// Note: we never clear items from the key locks, but this is so they can be re-used in the future without the cost
// of garbage collection
lock (_syncObj)
{
if (!_locksByKey.TryGetValue(key, out var asyncLock))
{
_locksByKey[key] = asyncLock = new AsyncLock();
}
return asyncLock;
}
}
/// <summary>
/// Called when the timer to clean up the cache elapsed.
/// </summary>
/// <param name="state">The timer state.</param>
private void OnTimerElapsed(object state)
{
if (!_checkForExpiredItems)
{
return;
}
RemoveExpiredItems();
}
/// <summary>
/// Remove item from cache by key.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="raiseEvents">Indicates whether events should be raised.</param>
/// <param name="action">The action that need to be executed in synchronization with the item cache removal.</param>
/// <returns>The value indicating whether the item was removed.</returns>
private bool RemoveItem(TKey key, bool raiseEvents, Action action = null)
{
// Try to get item, if there is no item by that key then return true to indicate that item was removed.
if (!_dictionary.TryGetValue(key, out var item))
{
return true;
}
action?.Invoke();
var cancel = false;
var expirationPolicy = item.ExpirationPolicy;
if (raiseEvents)
{
var expiringEventArgs = new ExpiringEventArgs<TKey, TValue>(key, item.Value, expirationPolicy);
Expiring?.Invoke(this, expiringEventArgs);
cancel = expiringEventArgs.Cancel;
expirationPolicy = expiringEventArgs.ExpirationPolicy;
}
if (cancel)
{
if (expirationPolicy is null && _defaultExpirationPolicyInitCode != null)
{
expirationPolicy = _defaultExpirationPolicyInitCode.Invoke();
}
_dictionary[key] = new CacheStorageValueInfo<TValue>(item.Value, expirationPolicy);
return false;
}
_dictionary.Remove(key);
var dispose = DisposeValuesOnRemoval;
if (raiseEvents)
{
var expiredEventArgs = new ExpiredEventArgs<TKey, TValue>(key, item.Value, dispose);
Expired?.Invoke(this, expiredEventArgs);
dispose = expiredEventArgs.Dispose;
}
if (dispose)
{
item.DisposeValue();
}
return true;
}
#endregion
}
}
| 38.35209 | 152 | 0.528317 | [
"MIT"
] | 14632791/Catel | src/Catel.Core/Caching/CacheStorage.cs | 23,857 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DimensionSystem : MonoBehaviour
{
public GameObject DimensionalFX;
public GameObject SwapFlash;
public AudioClip SwapSound;
public float Duration;
public float Cooldown;
// Singletons
public static DimensionSystem Instance;
// Private / Hidden variables..
[HideInInspector] public bool Drifted;
private float CooldownTimer;
private float DurationTimer;
private void Awake()
{
if (Instance != this && Instance != null) Destroy(Instance);
Instance = this;
}
private void Update() {
if(!PauseMenu.Instance.Paused) {
if(Input.GetKeyDown(KeyCode.X) && !this.GetComponent<HealthSystem>().IsDead) {
if(CooldownTimer <= 0f && !this.GetComponent<HealthSystem>().IsDead || Drifted && !this.GetComponent<HealthSystem>().IsDead) {
SwapDimension();
}else if(!this.GetComponent<HealthSystem>().IsDead) {
if(SubtitleController.Instance != null) SubtitleController.Instance.Show($"Dimensions on cooldown..", 1.75f);
}
}
if(CooldownTimer < 0f) CooldownTimer = 0f;
CooldownTimer -= Time.deltaTime;
if(Drifted) {
DurationTimer += Time.deltaTime;
if(DurationTimer >= Duration) {
if(SubtitleController.Instance != null) SubtitleController.Instance.Show($"oh snap", 1.75f);
CooldownTimer = Cooldown * 3f;
DurationTimer = 0f;
SwapDimension();
}
}else {
DurationTimer = 0f;
}
}
}
public void SwapDimension() {
Drifted = !Drifted;
CooldownTimer = Cooldown;
DimensionalFX.SetActive(Drifted);
SwapFlash.SetActive(true);
Camera.main.GetComponent<AudioSource>().PlayOneShot(SwapSound);
}
}
| 31.59375 | 142 | 0.589515 | [
"Apache-2.0"
] | Thev2Andy/DimensionalDrifter | Assets/Scripts/Dimensional Drifting/Drifter/DimensionSystem.cs | 2,024 | 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.Portal.Outputs
{
[OutputType]
public sealed class ConsolePropertiesResponse
{
/// <summary>
/// The operating system type of the cloud shell.
/// </summary>
public readonly string OsType;
/// <summary>
/// Provisioning state of the console.
/// </summary>
public readonly string ProvisioningState;
/// <summary>
/// Uri of the console.
/// </summary>
public readonly string Uri;
[OutputConstructor]
private ConsolePropertiesResponse(
string osType,
string provisioningState,
string uri)
{
OsType = osType;
ProvisioningState = provisioningState;
Uri = uri;
}
}
}
| 25.837209 | 81 | 0.60396 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/Portal/Outputs/ConsolePropertiesResponse.cs | 1,111 | 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.LinkWAN.Transform;
using Aliyun.Acs.LinkWAN.Transform.V20190301;
namespace Aliyun.Acs.LinkWAN.Model.V20190301
{
public class BindJoinPermissionToNodeGroupRequest : RpcAcsRequest<BindJoinPermissionToNodeGroupResponse>
{
public BindJoinPermissionToNodeGroupRequest()
: base("LinkWAN", "2019-03-01", "BindJoinPermissionToNodeGroup", "linkwan", "openAPI")
{
if (this.GetType().GetProperty("ProductEndpointMap") != null && this.GetType().GetProperty("ProductEndpointType") != null)
{
this.GetType().GetProperty("ProductEndpointMap").SetValue(this, Aliyun.Acs.LinkWAN.Endpoint.endpointMap, null);
this.GetType().GetProperty("ProductEndpointType").SetValue(this, Aliyun.Acs.LinkWAN.Endpoint.endpointRegionalType, null);
}
Protocol = ProtocolType.HTTPS;
Method = MethodType.POST;
}
private string joinPermissionId;
private string nodeGroupId;
public string JoinPermissionId
{
get
{
return joinPermissionId;
}
set
{
joinPermissionId = value;
DictionaryUtil.Add(QueryParameters, "JoinPermissionId", value);
}
}
public string NodeGroupId
{
get
{
return nodeGroupId;
}
set
{
nodeGroupId = value;
DictionaryUtil.Add(QueryParameters, "NodeGroupId", value);
}
}
public override bool CheckShowJsonItemName()
{
return false;
}
public override BindJoinPermissionToNodeGroupResponse GetResponse(UnmarshallerContext unmarshallerContext)
{
return BindJoinPermissionToNodeGroupResponseUnmarshaller.Unmarshall(unmarshallerContext);
}
}
}
| 31.517647 | 137 | 0.705487 | [
"Apache-2.0"
] | aliyun/aliyun-openapi-net-sdk | aliyun-net-sdk-linkwan/LinkWAN/Model/V20190301/BindJoinPermissionToNodeGroupRequest.cs | 2,679 | C# |
// *** WARNING: this file was generated by crd2pulumi. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Kubernetes.Types.Outputs.Certmanager.V1Beta1
{
[OutputType]
public sealed class IssuerSpecAcmeSolversSelector
{
/// <summary>
/// List of DNSNames that this solver will be used to solve. If specified and a match is found, a dnsNames selector will take precedence over a dnsZones selector. If multiple solvers match with the same dnsNames value, the solver with the most matching labels in matchLabels will be selected. If neither has more matches, the solver defined earlier in the list will be selected.
/// </summary>
public readonly ImmutableArray<string> DnsNames;
/// <summary>
/// List of DNSZones that this solver will be used to solve. The most specific DNS zone match specified here will take precedence over other DNS zone matches, so a solver specifying sys.example.com will be selected over one specifying example.com for the domain www.sys.example.com. If multiple solvers match with the same dnsZones value, the solver with the most matching labels in matchLabels will be selected. If neither has more matches, the solver defined earlier in the list will be selected.
/// </summary>
public readonly ImmutableArray<string> DnsZones;
/// <summary>
/// A label selector that is used to refine the set of certificate's that this challenge solver will apply to.
/// </summary>
public readonly ImmutableDictionary<string, string> MatchLabels;
[OutputConstructor]
private IssuerSpecAcmeSolversSelector(
ImmutableArray<string> dnsNames,
ImmutableArray<string> dnsZones,
ImmutableDictionary<string, string> matchLabels)
{
DnsNames = dnsNames;
DnsZones = dnsZones;
MatchLabels = matchLabels;
}
}
}
| 49.395349 | 506 | 0.708569 | [
"MIT"
] | WhereIsMyTransport/Pulumi.Crds.CertManager | crd/dotnet/Certmanager/V1Beta1/Outputs/IssuerSpecAcmeSolversSelector.cs | 2,124 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace Fish_Registration.Models.AccountViewModels
{
public class ExternalLoginViewModel
{
[Required]
[EmailAddress]
public string Email { get; set; }
}
}
| 21 | 52 | 0.729167 | [
"MIT"
] | thejohnjensen/fisher-registration | Fish-Registration/Models/AccountViewModels/ExternalLoginViewModel.cs | 336 | C# |
using Microsoft.AspNetCore.Components;
using Radzen.Blazor.Rendering;
using System;
namespace Radzen.Blazor
{
/// <summary>
/// Displays the appointments in a week day in <see cref="RadzenScheduler{TItem}" />
/// </summary>
/// <code>
/// <RadzenScheduler Data="@appointments">
/// <RadzenWeekView />
/// </RadzenScheduler>
/// </code>
public partial class RadzenWeekView : SchedulerViewBase
{
/// <inheritdoc />
public override string Icon => "calendar_view_week";
/// <inheritdoc />
[Parameter]
public override string Text { get; set; } = "Week";
/// <summary>
/// Gets or sets the time format.
/// </summary>
/// <value>The time format. Set to <c>h tt</c> by default.</value>
[Parameter]
public string TimeFormat { get; set; } = "h tt";
/// <summary>
/// Gets or sets the start time.
/// </summary>
/// <value>The start time.</value>
[Parameter]
public TimeSpan StartTime { get; set; } = TimeSpan.FromHours(8);
/// <summary>
/// Gets or sets the end time.
/// </summary>
/// <value>The end time.</value>
[Parameter]
public TimeSpan EndTime { get; set; } = TimeSpan.FromHours(24);
/// <summary>
/// Gets or sets slot size in minutes. Set to <c>30</c> by default.
/// </summary>
/// <value>The slot size in minutes.</value>
[Parameter]
public int MinutesPerSlot { get; set; } = 30;
/// <inheritdoc />
public override DateTime StartDate
{
get
{
return Scheduler.CurrentDate.Date.StartOfWeek();
}
}
/// <inheritdoc />
public override DateTime EndDate
{
get
{
return StartDate.EndOfWeek().AddDays(1);
}
}
/// <inheritdoc />
public override string Title
{
get
{
return $"{StartDate.ToString(Scheduler.Culture.DateTimeFormat.ShortDatePattern)} - {StartDate.EndOfWeek().ToString(Scheduler.Culture.DateTimeFormat.ShortDatePattern)}";
}
}
/// <inheritdoc />
public override DateTime Next()
{
return Scheduler.CurrentDate.Date.AddDays(7);
}
/// <inheritdoc />
public override DateTime Prev()
{
return Scheduler.CurrentDate.Date.AddDays(-7);
}
}
}
| 28.130435 | 184 | 0.525116 | [
"MIT"
] | AleSaiani/radzen-blazor | Radzen.Blazor/RadzenWeekView.razor.cs | 2,588 | C# |
namespace Epic.OnlineServices.Lobby
{
public class RejectInviteOptions
{
public int ApiVersion => 1;
public string InviteId { get; set; }
public ProductUserId LocalUserId { get; set; }
}
}
| 16.666667 | 48 | 0.72 | [
"MIT"
] | undancer/oni-data | Managed/firstpass/Epic/OnlineServices/Lobby/RejectInviteOptions.cs | 200 | 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.IO;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using stress.execution;
using stress.codegen.resources;
namespace stress.codegen
{
public class ExecutionFileGeneratorLinux : ISourceFileGenerator
{
private const string STRESS_SCRIPT_NAME = "stress.sh";
/*
* scriptName - name of the script to be generated, this should include the path
* testName - the name of the test executable
* arguments - arguments to be passed to the test executable
* envVars - dictionary of environment variables and their values
* host (optional) - needed for hosted runtimes
*/
public void GenerateSourceFile(LoadTestInfo loadTestInfo)
{
string shellScriptPath = Path.Combine(loadTestInfo.SourceDirectory, STRESS_SCRIPT_NAME);
using (TextWriter stressScript = new StreamWriter(shellScriptPath, false))
{
// set the line ending for shell scripts
stressScript.NewLine = "\n";
stressScript.WriteLine("#!/bin/sh");
stressScript.WriteLine();
stressScript.WriteLine();
stressScript.WriteLine("# stress script for {0}", loadTestInfo.TestName);
stressScript.WriteLine();
stressScript.WriteLine();
stressScript.WriteLine("# environment section");
// first take care of the environment variables
//if the environment variable "DUMPLING_PROPERTIES" already exists remove it
//this is needed because multiple LoadTestInfo objects use the same environment dictionary instance
if(loadTestInfo.EnvironmentVariables.ContainsKey("DUMPLING_PROPERTIES"))
{
loadTestInfo.EnvironmentVariables.Remove("DUMPLING_PROPERTIES");
}
// add environment variables STRESS_TESTID, STRESS_BUILDID
loadTestInfo.EnvironmentVariables["STRESS_TESTID"] = loadTestInfo.TestName;
loadTestInfo.EnvironmentVariables["STRESS_BUILDID"] = loadTestInfo.TestName.Split('_')[0];
// build a string of all the env var pairs to be passed as properties to dumpling
StringBuilder envVarPropertiesBuilder = new StringBuilder();
foreach (var kvp in loadTestInfo.EnvironmentVariables)
{
envVarPropertiesBuilder.Append(kvp.Key + "=" + kvp.Value + " ");
}
// add this string to the env vars as DUMPLING_PROPERTIES trimming the last space
loadTestInfo.EnvironmentVariables["DUMPLING_PROPERTIES"] = "\"" + envVarPropertiesBuilder.ToString().TrimEnd(' ') + "\"";
//write commands to setup environment environment
foreach (KeyValuePair<string, string> kvp in loadTestInfo.EnvironmentVariables)
{
stressScript.WriteLine("export {0}={1}", kvp.Key, kvp.Value);
}
stressScript.WriteLine();
stressScript.WriteLine();
// Prepare the test execution line
string testCommandLine = loadTestInfo.TestName + ".exe";
stressScript.WriteLine("chmod +x runstress.sh");
// If there is a host then prepend it to the test command line
if (!String.IsNullOrEmpty(loadTestInfo.SuiteConfig.Host))
{
stressScript.WriteLine($"chmod +x {loadTestInfo.SuiteConfig.Host}");
testCommandLine = loadTestInfo.SuiteConfig.Host + " " + testCommandLine;
// If the command line isn't a full path or ./ for current directory then add it to ensure we're using the host in the current directory
if ((!loadTestInfo.SuiteConfig.Host.StartsWith("/")) && (!loadTestInfo.SuiteConfig.Host.StartsWith("./")))
{
testCommandLine = "./" + testCommandLine;
}
}
testCommandLine = "./runstress.sh " + testCommandLine;
stressScript.WriteLine("#test execution");
stressScript.WriteLine("echo executing [{0}]", testCommandLine);
stressScript.WriteLine(testCommandLine);
// Save off the exit code
stressScript.WriteLine("export _EXITCODE=$?");
// exit the script with the return code
stressScript.WriteLine("exit $_EXITCODE");
}
// Add the shell script to the source files
loadTestInfo.SourceFiles.Add(new SourceFileInfo(STRESS_SCRIPT_NAME, SourceFileAction.Binplace));
//add runstress.sh to the source directory as well
var runstressPath = Path.Combine(loadTestInfo.SourceDirectory, "runstress.sh");
string unixContent = Encoding.UTF8.GetString(Resources.runstress).Replace("\r\n", "\n");
File.WriteAllText(runstressPath, unixContent);
//add runstress.sh to the source files
loadTestInfo.SourceFiles.Add(new SourceFileInfo("runstress.sh", SourceFileAction.Binplace));
}
}
public class ExecutionFileGeneratorWindows : ISourceFileGenerator
{
private const string STRESS_SCRIPT_NAME = "stress.bat";
public void GenerateSourceFile(LoadTestInfo loadTestInfo)// (string scriptName, string testName, Dictionary<string, string> envVars, string host = null)
{
string batchScriptPath = Path.Combine(loadTestInfo.SourceDirectory, STRESS_SCRIPT_NAME);
using (TextWriter stressScript = new StreamWriter(batchScriptPath, false))
{
stressScript.WriteLine("@echo off");
stressScript.WriteLine("REM stress script for " + loadTestInfo.TestName);
stressScript.WriteLine();
stressScript.WriteLine();
stressScript.WriteLine("REM environment section");
// first take care of the environment variables
foreach (KeyValuePair<string, string> kvp in loadTestInfo.EnvironmentVariables)
{
stressScript.WriteLine("set {0}={1}", kvp.Key, kvp.Value);
}
stressScript.WriteLine();
stressScript.WriteLine();
// Prepare the test execution line
string testCommandLine = loadTestInfo.TestName + ".exe";
// If there is a host then prepend it to the test command line
if (!String.IsNullOrEmpty(loadTestInfo.SuiteConfig.Host))
{
testCommandLine = loadTestInfo.SuiteConfig.Host + " " + testCommandLine;
}
stressScript.WriteLine("REM test execution");
stressScript.WriteLine("echo calling [{0}]", testCommandLine);
stressScript.WriteLine(testCommandLine);
// Save off the exit code
stressScript.WriteLine("set _EXITCODE=%ERRORLEVEL%");
stressScript.WriteLine("echo test exited with ExitCode: %_EXITCODE%");
stressScript.WriteLine();
stressScript.WriteLine();
// // Check the return code
// stressScript.WriteLine("if %_EXITCODE% EQU 0 goto :REPORT_PASS");
// stressScript.WriteLine("REM error processing");
// stressScript.WriteLine("echo JRS - Test Failed. Report the failure, call to do the initial dump analysis, zip up the directory and return that along with an event");
// stressScript.WriteLine("goto :END");
// stressScript.WriteLine();
// stressScript.WriteLine();
//
// stressScript.WriteLine(":REPORT_PASS");
// stressScript.WriteLine("echo JRS - Test Passed. Report the pass.");
// stressScript.WriteLine();
// stressScript.WriteLine();
// exit the script with the exit code from the process
stressScript.WriteLine(":END");
stressScript.WriteLine("exit /b %_EXITCODE%");
}
// Add the batch script to the source files
loadTestInfo.SourceFiles.Add(new SourceFileInfo(STRESS_SCRIPT_NAME, SourceFileAction.Binplace));
}
}
} | 48.84153 | 199 | 0.589617 | [
"MIT"
] | Bhaskers-Blu-Org2/dotnet-reliability | src/stress.codegen/ExecutionFileGenerator.cs | 8,938 | C# |
using System.Runtime.Serialization;
namespace Umbraco.Cms.Core.Models.ContentEditing
{
[DataContract(Name = "DomainDisplay")]
public class DomainDisplay
{
public DomainDisplay(string name, int lang)
{
Name = name;
Lang = lang;
}
[DataMember(Name = "name")]
public string Name { get; }
[DataMember(Name = "lang")]
public int Lang { get; }
[DataMember(Name = "duplicate")]
public bool Duplicate { get; set; }
[DataMember(Name = "other")]
public string Other { get; set; }
}
}
| 22.518519 | 51 | 0.559211 | [
"MIT"
] | Ambertvu/Umbraco-CMS | src/Umbraco.Core/Models/ContentEditing/DomainDisplay.cs | 610 | C# |
using UnityEngine;
namespace BehaviorDesigner.Runtime.Tasks.Basic.SharedVariables
{
[TaskCategory("Basic/SharedVariable")]
[TaskDescription("Sets the SharedFloat variable to the specified object. Returns Success.")]
public class SetSharedFloat : Action
{
[Tooltip("The value to set the SharedFloat to")]
public SharedFloat targetValue;
[RequiredField]
[Tooltip("The SharedFloat to set")]
public SharedFloat targetVariable;
public override TaskStatus OnUpdate()
{
targetVariable.Value = targetValue.Value;
return TaskStatus.Success;
}
public override void OnReset()
{
targetValue = 0;
targetVariable = 0;
}
}
} | 28.428571 | 97 | 0.610553 | [
"Apache-2.0"
] | brustlinker/unity_behaviortree_sk | Assets/Behavior Designer/Runtime/Basic Tasks/SharedVariables/SetSharedFloat.cs | 796 | C# |
// Copyright (c) Jeremy W. Kuhne. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace WInterop.Gdi
{
/// <summary>
/// Pen pixel mix modes (ROP2)
/// </summary>
public enum PenMixMode : int
{
// https://msdn.microsoft.com/en-us/library/cc234985.aspx
// https://msdn.microsoft.com/en-us/library/dd183369.aspx
/// <summary>
/// Pixel is always drawn black. [R2_BLACK]
/// </summary>
Black = 1,
/// <summary>
/// Inverse of result of MergePen. [R2_NOTMERGEPEN]
/// </summary>
NotMergePen = 2,
/// <summary>
/// The pixel is a combination of the colors that are common to both the screen and the inverse of the pen. [R2_MASKNOTPEN]
/// </summary>
MaskNotPen = 3,
/// <summary>
/// The pixel is the inverse of the pen color. [R2_NOTCOPYPEN]
/// </summary>
NotCopyPen = 4,
/// <summary>
/// The pixel is a combination of the colors that are common to both the pen and the inverse of the screen. [R2_MASKPENNOT]
/// </summary>
MaskPenNot = 5,
/// <summary>
/// The pixel is the inverse of the screen color. [R2_NOT]
/// </summary>
Not = 6,
/// <summary>
/// The pixel is a combination of the colors in the pen and in the screen, but not in both. [R2_XORPEN]
/// </summary>
XOrPen = 7,
/// <summary>
/// Inverse of the result of MaskPen. [R2_NOTMASKPEN]
/// </summary>
NotMaskPen = 8,
/// <summary>
/// The pixel is a combination of the colors that are common to both the pen and the screen. [R2_MASKPEN]
/// </summary>
MaskPen = 9,
/// <summary>
/// Inverse of the result of XOrPen. [R2_NOTXORPEN]
/// </summary>
NotXOrPen = 10,
/// <summary>
/// The pixel remains unchanged. [R2_NOP]
/// </summary>
Nop = 11,
/// <summary>
/// The pixel is a combination of the screen color and the inverse of the pen color. [R2_MERGENOTPEN]
/// </summary>
MergeNotPen = 12,
/// <summary>
/// The pixel always has the color of the pen. [R2_COPYPEN]
/// </summary>
CopyPen = 13,
/// <summary>
/// The pixel is a combination of the pen color and the inverse of the screen color. [R2_MERGEPENNOT]
/// </summary>
MergePenNot = 14,
/// <summary>
/// The pixel is a combination of the pen color and the screen color. [R2_MERGEPEN]
/// </summary>
MergePen = 15,
/// <summary>
/// The pixel is always drawn as white. [R2_WHITE]
/// </summary>
White = 16
}
} | 30.787234 | 132 | 0.541811 | [
"MIT"
] | JeremyKuhne/WInterop | src/WInterop.Desktop/Gdi/PenMixMode.cs | 2,896 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.DocAsCode.Metadata.ManagedReference
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;
using Microsoft.DocAsCode.Common;
using Microsoft.DocAsCode.Plugins;
using Microsoft.DocAsCode.DataContracts.ManagedReference;
using System.Globalization;
public class TripleSlashCommentModel
{
private const string idSelector = @"((?![0-9])[\w_])+[\w\(\)\.\{\}\[\]\|\*\^~#@!`,_<>:]*";
private static readonly Regex CommentIdRegex = new Regex(@"^(?<type>N|T|M|P|F|E|Overload):(?<id>" + idSelector + ")$", RegexOptions.Compiled);
private static readonly Regex LineBreakRegex = new Regex(@"\r?\n", RegexOptions.Compiled);
private static readonly Regex CodeElementRegex = new Regex(@"<code[^>]*>([\s\S]*?)</code>", RegexOptions.Compiled);
private static readonly Regex RegionRegex = new Regex(@"^\s*#region\s*(.*)$");
private static readonly Regex XmlRegionRegex = new Regex(@"^\s*<!--\s*<([^/\s].*)>\s*-->$");
private static readonly Regex EndRegionRegex = new Regex(@"^\s*#endregion\s*.*$");
private static readonly Regex XmlEndRegionRegex = new Regex(@"^\s*<!--\s*</(.*)>\s*-->$");
private readonly ITripleSlashCommentParserContext _context;
public string Summary { get; private set; }
public string Remarks { get; private set; }
public string Returns { get; private set; }
public List<ExceptionInfo> Exceptions { get; private set; }
public List<LinkInfo> Sees { get; private set; }
public List<LinkInfo> SeeAlsos { get; private set; }
public List<string> Examples { get; private set; }
public Dictionary<string, string> Parameters { get; private set; }
public Dictionary<string, string> TypeParameters { get; private set; }
public bool IsInheritDoc { get; private set; }
private TripleSlashCommentModel(string xml, SyntaxLanguage language, ITripleSlashCommentParserContext context)
{
// Transform triple slash comment
XDocument doc = TripleSlashCommentTransformer.Transform(xml, language);
_context = context;
if (!context.PreserveRawInlineComments)
{
ResolveSeeCref(doc, context.AddReferenceDelegate, context.ResolveCRef);
ResolveSeeAlsoCref(doc, context.AddReferenceDelegate, context.ResolveCRef);
ResolveExceptionCref(doc, context.AddReferenceDelegate, context.ResolveCRef);
}
ResolveCodeSource(doc, context);
var nav = doc.CreateNavigator();
Summary = GetSummary(nav, context);
Remarks = GetRemarks(nav, context);
Returns = GetReturns(nav, context);
Exceptions = GetExceptions(nav, context);
Sees = GetSees(nav, context);
SeeAlsos = GetSeeAlsos(nav, context);
Examples = GetExamples(nav, context);
Parameters = GetParameters(nav, context);
TypeParameters = GetTypeParameters(nav, context);
IsInheritDoc = GetIsInheritDoc(nav, context);
}
public static TripleSlashCommentModel CreateModel(string xml, SyntaxLanguage language, ITripleSlashCommentParserContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (string.IsNullOrEmpty(xml)) return null;
// Quick turnaround for badly formed XML comment
if (xml.StartsWith("<!-- Badly formed XML comment ignored for member ", StringComparison.Ordinal))
{
Logger.LogWarning($"Invalid triple slash comment is ignored: {xml}");
return null;
}
try
{
var model = new TripleSlashCommentModel(xml, language, context);
return model;
}
catch (XmlException)
{
return null;
}
}
public void CopyInheritedData(TripleSlashCommentModel src)
{
if (src == null)
{
throw new ArgumentNullException(nameof(src));
}
Summary = Summary ?? src.Summary;
Remarks = Remarks ?? src.Remarks;
Returns = Returns ?? src.Returns;
if (Exceptions == null && src.Exceptions != null)
{
Exceptions = src.Exceptions.Select(e => e.Clone()).ToList();
}
if (Sees == null && src.Sees != null)
{
Sees = src.Sees.Select(s => s.Clone()).ToList();
}
if (SeeAlsos == null && src.SeeAlsos != null)
{
SeeAlsos = src.SeeAlsos.Select(s => s.Clone()).ToList();
}
if (Examples == null && src.Examples != null)
{
Examples = new List<string>(src.Examples);
}
if (Parameters == null && src.Parameters != null)
{
Parameters = new Dictionary<string, string>(src.Parameters);
}
if (TypeParameters == null && src.TypeParameters != null)
{
TypeParameters = new Dictionary<string, string>(src.TypeParameters);
}
}
public string GetParameter(string name)
{
if (string.IsNullOrEmpty(name))
{
return null;
}
return GetValue(name, Parameters);
}
public string GetTypeParameter(string name)
{
if (string.IsNullOrEmpty(name))
{
return null;
}
return GetValue(name, TypeParameters);
}
private static string GetValue(string name, Dictionary<string, string> dictionary)
{
if (dictionary == null)
{
return null;
}
if (dictionary.TryGetValue(name, out string description))
{
return description;
}
return null;
}
/// <summary>
/// Get summary node out from triple slash comments
/// </summary>
/// <param name="xml"></param>
/// <param name="normalize"></param>
/// <returns></returns>
/// <example>
/// <code> <see cref="Hello"/></code>
/// </example>
private string GetSummary(XPathNavigator nav, ITripleSlashCommentParserContext context)
{
// Resolve <see cref> to @ syntax
// Also support <seealso cref>
string selector = "/member/summary";
return GetSingleNodeValue(nav, selector);
}
/// <summary>
/// Get remarks node out from triple slash comments
/// </summary>
/// <remarks>
/// <para>This is a sample of exception node</para>
/// </remarks>
/// <param name="xml"></param>
/// <param name="normalize"></param>
/// <returns></returns>
private string GetRemarks(XPathNavigator nav, ITripleSlashCommentParserContext context)
{
string selector = "/member/remarks";
return GetSingleNodeValue(nav, selector);
}
private string GetReturns(XPathNavigator nav, ITripleSlashCommentParserContext context)
{
// Resolve <see cref> to @ syntax
// Also support <seealso cref>
string selector = "/member/returns";
return GetSingleNodeValue(nav, selector);
}
/// <summary>
/// Get exceptions nodes out from triple slash comments
/// </summary>
/// <param name="xml"></param>
/// <param name="normalize"></param>
/// <returns></returns>
/// <exception cref="XmlException">This is a sample of exception node</exception>
private List<ExceptionInfo> GetExceptions(XPathNavigator nav, ITripleSlashCommentParserContext context)
{
string selector = "/member/exception";
var result = GetMulitpleCrefInfo(nav, selector).ToList();
if (result.Count == 0)
{
return null;
}
return result;
}
/// <summary>
/// To get `see` tags out
/// </summary>
/// <param name="xml"></param>
/// <param name="context"></param>
/// <returns></returns>
/// <see cref="SpecIdHelper"/>
/// <see cref="SourceSwitch"/>
private List<LinkInfo> GetSees(XPathNavigator nav, ITripleSlashCommentParserContext context)
{
var result = GetMultipleLinkInfo(nav, "/member/see").ToList();
if (result.Count == 0)
{
return null;
}
return result;
}
/// <summary>
/// To get `seealso` tags out
/// </summary>
/// <param name="xml"></param>
/// <param name="context"></param>
/// <returns></returns>
/// <seealso cref="WaitForChangedResult"/>
/// <seealso cref="http://google.com">ABCS</seealso>
private List<LinkInfo> GetSeeAlsos(XPathNavigator nav, ITripleSlashCommentParserContext context)
{
var result = GetMultipleLinkInfo(nav, "/member/seealso").ToList();
if (result.Count == 0)
{
return null;
}
return result;
}
/// <summary>
/// To get `example` tags out
/// </summary>
/// <param name="xml"></param>
/// <param name="context"></param>
/// <returns></returns>
/// <example>
/// This sample shows how to call the <see cref="GetExceptions(string, ITripleSlashCommentParserContext)"/> method.
/// <code>
/// class TestClass
/// {
/// static int Main()
/// {
/// return GetExceptions(null, null).Count();
/// }
/// }
/// </code>
/// </example>
private List<string> GetExamples(XPathNavigator nav, ITripleSlashCommentParserContext context)
{
// Resolve <see cref> to @ syntax
// Also support <seealso cref>
return GetMultipleExampleNodes(nav, "/member/example").ToList();
}
private bool GetIsInheritDoc(XPathNavigator nav, ITripleSlashCommentParserContext context)
{
var node = nav.SelectSingleNode("/member/inheritdoc");
if (node == null)
{
return false;
}
if (node.HasAttributes)
{
//The Sandcastle implementation of <inheritdoc /> supports two attributes: 'cref' and 'select'.
//These attributes allow changing the source of the inherited doc and controlling what is inherited.
//Until these attributes are supported, ignoring inheritdoc elements with attributes, so as not to misinterpret them.
Logger.LogWarning("Attributes on <inheritdoc /> elements are not supported; inheritdoc element will be ignored.");
return false;
}
return true;
}
private void ResolveCodeSource(XDocument doc, ITripleSlashCommentParserContext context)
{
foreach (XElement node in doc.XPathSelectElements("//code"))
{
var source = node.Attribute("source");
if (source == null || string.IsNullOrEmpty(source.Value))
{
continue;
}
if (context.Source == null || string.IsNullOrEmpty(context.Source.Path))
{
Logger.LogWarning($"Unable to get source file path for {node.ToString()}");
return;
}
var region = node.Attribute("region");
var path = source.Value;
if (!Path.IsPathRooted(path))
{
var basePath = !string.IsNullOrEmpty(context.CodeSourceBasePath) ? context.CodeSourceBasePath : Path.GetDirectoryName(Path.Combine(EnvironmentContext.BaseDirectory, context.Source.Path));
path = Path.Combine(basePath, path);
}
ResolveCodeSource(node, path, region?.Value);
}
}
private void ResolveCodeSource(XElement element, string source, string region)
{
if (!File.Exists(source))
{
Logger.LogWarning($"Source file '{source}' not found.");
return;
}
var (regionRegex, endRegionRegex) = GetRegionRegex(source);
var builder = new StringBuilder();
var regionCount = 0;
foreach (var line in File.ReadLines(source))
{
if (!string.IsNullOrEmpty(region))
{
var match = regionRegex.Match(line);
if (match.Success)
{
var name = match.Groups[1].Value.Trim();
if (name == region)
{
++regionCount;
continue;
}
else if (regionCount > 0)
{
++regionCount;
}
}
else if (regionCount > 0 && endRegionRegex.IsMatch(line))
{
--regionCount;
if (regionCount == 0)
{
break;
}
}
if (regionCount > 0)
{
builder.AppendLine(line);
}
}
else
{
builder.AppendLine(line);
}
}
element.SetValue(builder.ToString());
}
private Dictionary<string, string> GetListContent(XPathNavigator navigator, string xpath, string contentType, ITripleSlashCommentParserContext context)
{
var iterator = navigator.Select(xpath);
var result = new Dictionary<string, string>();
if (iterator == null)
{
return result;
}
foreach (XPathNavigator nav in iterator)
{
string name = nav.GetAttribute("name", string.Empty);
string description = GetXmlValue(nav);
if (!string.IsNullOrEmpty(name))
{
if (result.ContainsKey(name))
{
string path = context.Source.Remote != null ? Path.Combine(EnvironmentContext.BaseDirectory, context.Source.Remote.RelativePath) : context.Source.Path;
Logger.LogWarning($"Duplicate {contentType} '{name}' found in comments, the latter one is ignored.", file: StringExtension.ToDisplayPath(path), line: context.Source.StartLine.ToString());
}
else
{
result.Add(name, description);
}
}
}
return result;
}
private Dictionary<string, string> GetParameters(XPathNavigator navigator, ITripleSlashCommentParserContext context)
{
return GetListContent(navigator, "/member/param", "parameter", context);
}
private static (Regex, Regex) GetRegionRegex(String source)
{
var ext = Path.GetExtension(source);
switch (ext.ToUpper())
{
case ".XML":
case ".XAML":
case ".HTML":
case ".CSHTML":
case ".VBHTML":
return (XmlRegionRegex, XmlEndRegionRegex);
}
return (RegionRegex, EndRegionRegex);
}
private Dictionary<string, string> GetTypeParameters(XPathNavigator navigator, ITripleSlashCommentParserContext context)
{
return GetListContent(navigator, "/member/typeparam", "type parameter", context);
}
private void ResolveSeeAlsoCref(XNode node, Action<string, string> addReference, Func<string, CRefTarget> resolveCRef)
{
// Resolve <see cref> to <xref>
ResolveCrefLink(node, "//seealso[@cref]", addReference, resolveCRef);
}
private void ResolveSeeCref(XNode node, Action<string, string> addReference, Func<string, CRefTarget> resolveCRef)
{
// Resolve <see cref> to <xref>
ResolveCrefLink(node, "//see[@cref]", addReference, resolveCRef);
}
private void ResolveExceptionCref(XNode node, Action<string, string> addReference, Func<string, CRefTarget> resolveCRef)
{
ResolveCrefLink(node, "//exception[@cref]", addReference, resolveCRef);
}
private void ResolveCrefLink(XNode node, string nodeSelector, Action<string, string> addReference, Func<string, CRefTarget> resolveCRef)
{
if (node == null || string.IsNullOrEmpty(nodeSelector))
{
return;
}
try
{
var nodes = node.XPathSelectElements(nodeSelector + "[@cref]").ToList();
foreach (var item in nodes)
{
var cref = item.Attribute("cref").Value;
var success = false;
if (resolveCRef != null)
{
// The resolveCRef delegate resolves the cref and returns the name of a reference if successful.
var cRefTarget = resolveCRef.Invoke(cref);
if (cRefTarget != null)
{
if (item.Parent?.Parent == null)
{
// <see> or <seealso> is top-level tag. Keep it, but set resolved references.
item.SetAttributeValue("refId", cRefTarget.Id);
item.SetAttributeValue("cref", cRefTarget.CommentId);
}
else
{
// <see> occurs in text. Replace it with an <xref> node using the resolved reference.
var replacement = XElement.Parse($"<xref href=\"{HttpUtility.UrlEncode(cRefTarget.Id)}\" data-throw-if-not-resolved=\"false\"></xref>");
item.ReplaceWith(replacement);
}
success = true;
}
else
{
item.Remove();
success = false;
}
}
else
{
// Strict check is needed as value could be an invalid href,
// e.g. !:Dictionary<TKey, string> when user manually changed the intellisensed generic type
var match = CommentIdRegex.Match(cref);
if (match.Success)
{
var id = match.Groups["id"].Value;
var type = match.Groups["type"].Value;
if (type == "Overload")
{
id += '*';
}
// When see and seealso are top level nodes in triple slash comments, do not convert it into xref node
if (item.Parent?.Parent != null)
{
var replacement = XElement.Parse($"<xref href=\"{HttpUtility.UrlEncode(id)}\" data-throw-if-not-resolved=\"false\"></xref>");
item.ReplaceWith(replacement);
}
addReference?.Invoke(id, cref);
success = true;
}
}
if (!success)
{
var detailedInfo = new StringBuilder();
if (_context != null && _context.Source != null)
{
if (!string.IsNullOrEmpty(_context.Source.Name))
{
detailedInfo.Append(" for ");
detailedInfo.Append(_context.Source.Name);
}
if (!string.IsNullOrEmpty(_context.Source.Path))
{
detailedInfo.Append(" defined in ");
detailedInfo.Append(_context.Source.Path);
detailedInfo.Append(" Line ");
detailedInfo.Append(_context.Source.StartLine);
}
}
Logger.Log(LogLevel.Warning, $"Invalid cref value \"{cref}\" found in triple-slash-comments{detailedInfo}, ignored.");
}
}
}
catch
{
}
}
private IEnumerable<string> GetMultipleExampleNodes(XPathNavigator navigator, string selector)
{
var iterator = navigator.Select(selector);
if (iterator == null)
{
yield break;
}
foreach (XPathNavigator nav in iterator)
{
string description = GetXmlValue(nav);
yield return description;
}
}
private IEnumerable<ExceptionInfo> GetMulitpleCrefInfo(XPathNavigator navigator, string selector)
{
var iterator = navigator.Clone().Select(selector);
if (iterator == null)
{
yield break;
}
foreach (XPathNavigator nav in iterator)
{
string description = GetXmlValue(nav);
if (string.IsNullOrEmpty(description))
{
description = null;
}
string commentId = nav.GetAttribute("cref", string.Empty);
string refId = nav.GetAttribute("refId", string.Empty);
if (!string.IsNullOrEmpty(refId))
{
yield return new ExceptionInfo
{
Description = description,
Type = refId,
CommentId = commentId
};
}
else if (!string.IsNullOrEmpty(commentId))
{
// Check if exception type is valid and trim prefix
var match = CommentIdRegex.Match(commentId);
if (match.Success)
{
var id = match.Groups["id"].Value;
var type = match.Groups["type"].Value;
if (type == "T")
{
yield return new ExceptionInfo
{
Description = description,
Type = id,
CommentId = commentId
};
}
}
}
}
}
private IEnumerable<LinkInfo> GetMultipleLinkInfo(XPathNavigator navigator, string selector)
{
var iterator = navigator.Clone().Select(selector);
if (iterator == null)
{
yield break;
}
foreach (XPathNavigator nav in iterator)
{
string altText = GetXmlValue(nav);
if (string.IsNullOrEmpty(altText))
{
altText = null;
}
string commentId = nav.GetAttribute("cref", string.Empty);
string url = nav.GetAttribute("href", string.Empty);
string refId = nav.GetAttribute("refId", string.Empty);
if (!string.IsNullOrEmpty(refId))
{
yield return new LinkInfo
{
AltText = altText,
LinkId = refId,
CommentId = commentId,
LinkType = LinkType.CRef
};
}
else if (!string.IsNullOrEmpty(commentId))
{
// Check if cref type is valid and trim prefix
var match = CommentIdRegex.Match(commentId);
if (match.Success)
{
var id = match.Groups["id"].Value;
var type = match.Groups["type"].Value;
if (type == "Overload")
{
id += '*';
}
yield return new LinkInfo
{
AltText = altText,
LinkId = id,
CommentId = commentId,
LinkType = LinkType.CRef
};
}
}
else if (!string.IsNullOrEmpty(url))
{
yield return new LinkInfo
{
AltText = altText ?? url,
LinkId = url,
LinkType = LinkType.HRef
};
}
}
}
private string GetSingleNodeValue(XPathNavigator nav, string selector)
{
var node = nav.Clone().SelectSingleNode(selector);
if (node == null)
{
// throw new ArgumentException(selector + " is not found");
return null;
}
else
{
return GetXmlValue(node);
}
}
private string GetXmlValue(XPathNavigator node)
{
// NOTE: use node.InnerXml instead of node.Value, to keep decorative nodes,
// e.g.
// <remarks><para>Value</para></remarks>
// decode InnerXml as it encodes
// IXmlLineInfo.LinePosition starts from 1 and it would ignore '<'
// e.g.
// <summary/> the LinePosition is the column number of 's', so it should be minus 2
var lineInfo = node as IXmlLineInfo;
int column = lineInfo.HasLineInfo() ? lineInfo.LinePosition - 2 : 0;
return NormalizeXml(RemoveLeadingSpaces(GetInnerXml(node)), column);
}
/// <summary>
/// Remove least common whitespces in each line of xml
/// </summary>
/// <param name="xml"></param>
/// <returns>xml after removing least common whitespaces</returns>
private static string RemoveLeadingSpaces(string xml)
{
var lines = LineBreakRegex.Split(xml);
var normalized = new List<string>();
var preIndex = 0;
var leadingSpaces = from line in lines
where !string.IsNullOrWhiteSpace(line)
select line.TakeWhile(char.IsWhiteSpace).Count();
if (leadingSpaces.Any())
{
preIndex = leadingSpaces.Min();
}
if (preIndex == 0)
{
return xml;
}
foreach (var line in lines)
{
if (string.IsNullOrWhiteSpace(line))
{
normalized.Add(string.Empty);
}
else
{
normalized.Add(line.Substring(preIndex));
}
}
return string.Join("\n", normalized);
}
/// <summary>
/// Split xml into lines. Trim meaningless whitespaces.
/// if a line starts with xml node, all leading whitespaces would be trimmed
/// otherwise text node start position always aligns with the start position of its parent line(the last previous line that starts with xml node)
/// Trim newline character for code element.
/// </summary>
/// <param name="xml"></param>
/// <param name="parentIndex">the start position of the last previous line that starts with xml node</param>
/// <returns>normalized xml</returns>
private static string NormalizeXml(string xml, int parentIndex)
{
var lines = LineBreakRegex.Split(xml);
var normalized = new List<string>();
foreach (var line in lines)
{
if (string.IsNullOrWhiteSpace(line))
{
normalized.Add(string.Empty);
}
else
{
// TO-DO: special logic for TAB case
int index = line.TakeWhile(char.IsWhiteSpace).Count();
if (line[index] == '<')
{
parentIndex = index;
}
normalized.Add(line.Substring(Math.Min(parentIndex, index)));
}
}
// trim newline character for code element
return CodeElementRegex.Replace(
string.Join("\n", normalized),
m =>
{
var group = m.Groups[1];
if (group.Length == 0)
{
return m.Value;
}
return m.Value.Replace(group.ToString(), group.ToString().Trim('\n'));
});
}
/// <summary>
/// `>` is always encoded to `>` in XML, when triple-slash-comments is considered as Markdown content, `>` is considered as blockquote
/// Decode `>` to enable the Markdown syntax considering `>` is not a Must-Encode in Text XElement
/// </summary>
/// <param name="node"></param>
/// <returns></returns>
private static string GetInnerXml(XPathNavigator node)
{
using (var sw = new StringWriter(CultureInfo.InvariantCulture))
{
using (var tw = new XmlWriterWithGtDecoded(sw))
{
if (node.MoveToFirstChild())
{
do
{
tw.WriteNode(node, true);
} while (node.MoveToNext());
node.MoveToParent();
}
}
return sw.ToString();
}
}
private sealed class XmlWriterWithGtDecoded : XmlTextWriter
{
public XmlWriterWithGtDecoded(TextWriter tw) : base(tw) { }
public XmlWriterWithGtDecoded(Stream w, Encoding encoding) : base(w, encoding) { }
public override void WriteString(string text)
{
var encoded = text.Replace("&", "&").Replace("<", "<").Replace("'", "'").Replace("\"", """);
WriteRaw(encoded);
}
}
}
}
| 39.469679 | 212 | 0.471049 | [
"MIT"
] | Ermerson/docfx | src/Microsoft.DocAsCode.Metadata.ManagedReference.Common/Parsers/TripleSlashCommentModel.cs | 32,354 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections;
using System.Collections.Generic;
using Dbg = System.Diagnostics.Debug;
using System.Management.Automation;
using Microsoft.PowerShell.PowerShellGet.UtilClasses;
namespace Microsoft.PowerShell.PowerShellGet.Cmdlets
{
/// <summary>
/// The Set-PSResourceRepository cmdlet is used to set information for a repository.
/// </summary>
[Cmdlet(VerbsCommon.Set,
"PSResourceRepository",
DefaultParameterSetName = NameParameterSet,
SupportsShouldProcess = true)]
public sealed
class SetPSResourceRepository : PSCmdlet
{
#region Members
private const string NameParameterSet = "NameParameterSet";
private const string RepositoriesParameterSet = "RepositoriesParameterSet";
private const int DefaultPriority = -1;
private Uri _url;
#endregion
#region Parameters
/// <summary>
/// Specifies the name of the repository to be set.
/// </sumamry>
[Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true, ParameterSetName = NameParameterSet)]
[ArgumentCompleter(typeof(RepositoryNameCompleter))]
[ValidateNotNullOrEmpty]
public string Name { get; set; }
/// <summary>
/// Specifies the location of the repository to be set.
/// </sumamry>
[Parameter(ParameterSetName = NameParameterSet)]
[ValidateNotNullOrEmpty]
public string URL { get; set; }
/// <summary>
/// Specifies a hashtable of repositories and is used to register multiple repositories at once.
/// </summary>
[Parameter(Mandatory = true, ParameterSetName = RepositoriesParameterSet)]
[ValidateNotNullOrEmpty]
public Hashtable[] Repositories { get; set; }
/// <summary>
/// Specifies whether the repository should be trusted.
/// </summary>
[Parameter(ParameterSetName = NameParameterSet)]
public SwitchParameter Trusted
{
get
{ return _trusted; }
set
{
_trusted = value;
isSet = true;
}
}
private SwitchParameter _trusted;
private bool isSet;
/// <summary>
/// Specifies the priority ranking of the repository, such that repositories with higher ranking priority are searched
/// before a lower ranking priority one, when searching for a repository item across multiple registered repositories.
/// Valid priority values range from 0 to 50, such that a lower numeric value (i.e 10) corresponds
/// to a higher priority ranking than a higher numeric value (i.e 40).
/// </summary>
[Parameter(ParameterSetName = NameParameterSet)]
[ValidateNotNullOrEmpty]
[ValidateRange(0, 50)]
public int Priority { get; set; } = DefaultPriority;
/// <summary>
/// When specified, displays the succcessfully registered repository and its information
/// </summary>
[Parameter]
public SwitchParameter PassThru { get; set; }
#endregion
#region Methods
protected override void BeginProcessing()
{
RepositorySettings.CheckRepositoryStore();
}
protected override void ProcessRecord()
{
if (MyInvocation.BoundParameters.ContainsKey(nameof(URL)))
{
bool isUrlValid = Utils.TryCreateValidUrl(URL, this, out _url, out ErrorRecord errorRecord);
if (!isUrlValid)
{
ThrowTerminatingError(errorRecord);
}
}
List<PSRepositoryInfo> items = new List<PSRepositoryInfo>();
switch(ParameterSetName)
{
case NameParameterSet:
try
{
items.Add(UpdateRepositoryStoreHelper(Name, _url, Priority, Trusted));
}
catch (Exception e)
{
ThrowTerminatingError(new ErrorRecord(
new PSInvalidOperationException(e.Message),
"ErrorInNameParameterSet",
ErrorCategory.InvalidArgument,
this));
}
break;
case RepositoriesParameterSet:
try
{
items = RepositoriesParameterSetHelper();
}
catch (Exception e)
{
ThrowTerminatingError(new ErrorRecord(
new PSInvalidOperationException(e.Message),
"ErrorInRepositoriesParameterSet",
ErrorCategory.InvalidArgument,
this));
}
break;
default:
Dbg.Assert(false, "Invalid parameter set");
break;
}
if (PassThru)
{
foreach(PSRepositoryInfo item in items)
{
WriteObject(item);
}
}
}
private PSRepositoryInfo UpdateRepositoryStoreHelper(string repoName, Uri repoUrl, int repoPriority, bool repoTrusted)
{
if (repoUrl != null && !(repoUrl.Scheme == Uri.UriSchemeHttp || repoUrl.Scheme == Uri.UriSchemeHttps || repoUrl.Scheme == Uri.UriSchemeFtp || repoUrl.Scheme == Uri.UriSchemeFile))
{
throw new ArgumentException("Invalid url, must be one of the following Uri schemes: HTTPS, HTTP, FTP, File Based");
}
// check repoName can't contain * or just be whitespace
// remove trailing and leading whitespaces, and if Name is just whitespace Name should become null now and be caught by following condition
repoName = repoName.Trim();
if (String.IsNullOrEmpty(repoName) || repoName.Contains("*"))
{
throw new ArgumentException("Name cannot be null/empty, contain asterisk or be just whitespace");
}
// check PSGallery URL is not trying to be set
if (repoName.Equals("PSGallery", StringComparison.OrdinalIgnoreCase) && repoUrl != null)
{
throw new ArgumentException("The PSGallery repository has a pre-defined URL. Setting the -URL parmeter for this repository is not allowed, instead try running 'Register-PSResourceRepository -PSGallery'.");
}
// determine trusted value to pass in (true/false if set, null otherwise, hence the nullable bool variable)
bool? _trustedNullable = isSet ? new bool?(repoTrusted) : new bool?();
// determine if either 1 of 3 values are attempting to be set: URL, Priority, Trusted.
// if none are (i.e only Name parameter was provided, write error)
if(repoUrl == null && repoPriority == DefaultPriority && _trustedNullable == null)
{
throw new ArgumentException("Either URL, Priority or Trusted parameters must be requested to be set");
}
WriteVerbose("All required values to set repository provided, calling internal Update() API now");
if (!ShouldProcess(repoName, "Set repository's value(s) in repository store"))
{
return null;
}
return RepositorySettings.Update(repoName, repoUrl, repoPriority, _trustedNullable);
}
private List<PSRepositoryInfo> RepositoriesParameterSetHelper()
{
List<PSRepositoryInfo> reposUpdatedFromHashtable = new List<PSRepositoryInfo>();
foreach (Hashtable repo in Repositories)
{
if (!repo.ContainsKey("Name") || repo["Name"] == null || String.IsNullOrEmpty(repo["Name"].ToString()))
{
WriteError(new ErrorRecord(
new PSInvalidOperationException("Repository hashtable must contain Name key value pair"),
"NullNameForRepositoriesParameterSetRepo",
ErrorCategory.InvalidArgument,
this));
continue;
}
PSRepositoryInfo parsedRepoAdded = RepoValidationHelper(repo);
if (parsedRepoAdded != null)
{
reposUpdatedFromHashtable.Add(parsedRepoAdded);
}
}
return reposUpdatedFromHashtable;
}
private PSRepositoryInfo RepoValidationHelper(Hashtable repo)
{
WriteVerbose(String.Format("Parsing through repository: {0}", repo["Name"]));
Uri repoURL = null;
if (repo.ContainsKey("Url"))
{
if (String.IsNullOrEmpty(repo["Url"].ToString()))
{
WriteError(new ErrorRecord(
new PSInvalidOperationException("Repository url cannot be null if provided"),
"NullURLForRepositoriesParameterSetUpdate",
ErrorCategory.InvalidArgument,
this));
return null;
}
if (!Utils.TryCreateValidUrl(uriString: repo["Url"].ToString(),
cmdletPassedIn: this,
uriResult: out repoURL,
errorRecord: out ErrorRecord errorRecord))
{
WriteError(errorRecord);
return null;
}
}
bool repoTrusted = false;
isSet = false;
if(repo.ContainsKey("Trusted"))
{
repoTrusted = (bool) repo["Trusted"];
isSet = true;
}
try
{
return UpdateRepositoryStoreHelper(repo["Name"].ToString(),
repoURL,
repo.ContainsKey("Priority") ? Convert.ToInt32(repo["Priority"].ToString()) : DefaultPriority,
repoTrusted);
}
catch (Exception e)
{
WriteError(new ErrorRecord(
new PSInvalidOperationException(e.Message),
"ErrorSettingIndividualRepoFromRepositories",
ErrorCategory.InvalidArgument,
this));
return null;
}
}
#endregion
}
}
| 39.545455 | 222 | 0.550897 | [
"MIT"
] | Seanpm2001-Microsoft/PowerShellGet | src/code/SetPSResourceRepository.cs | 10,875 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Poseidon.Core.IDAL
{
using Poseidon.Base.Framework;
using Poseidon.Core.DL;
/// <summary>
/// 菜单对象访问接口
/// </summary>
internal interface IMenuRepository : IBaseDAL<Menu>
{
}
}
| 17.736842 | 55 | 0.68546 | [
"MIT"
] | robertzml/Poseidon | Poseidon.Core/IDAL/IMenuRepository.cs | 355 | 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;
namespace Lucene.Net.Index
{
abstract class InvertedDocConsumerPerThread
{
public abstract void StartDocument();
internal abstract InvertedDocConsumerPerField AddField(DocInverterPerField docInverterPerField, FieldInfo fieldInfo);
public abstract DocumentsWriter.DocWriter FinishDocument();
public abstract void Abort();
}
} | 38.533333 | 119 | 0.774221 | [
"Apache-2.0"
] | Distrotech/mono | external/Lucene.Net/src/core/Index/InvertedDocConsumerPerThread.cs | 1,156 | 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.Compute.V20171201
{
public static class GetAvailabilitySet
{
/// <summary>
/// Specifies information about the availability set that the virtual machine should be assigned to. Virtual machines specified in the same availability set are allocated to different nodes to maximize availability. For more information about availability sets, see [Manage the availability of virtual machines](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-windows-manage-availability?toc=%2fazure%2fvirtual-machines%2fwindows%2ftoc.json). <br><br> For more information on Azure planned maintenance, see [Planned maintenance for virtual machines in Azure](https://docs.microsoft.com/azure/virtual-machines/virtual-machines-windows-planned-maintenance?toc=%2fazure%2fvirtual-machines%2fwindows%2ftoc.json) <br><br> Currently, a VM can only be added to availability set at creation time. An existing VM cannot be added to an availability set.
/// </summary>
public static Task<GetAvailabilitySetResult> InvokeAsync(GetAvailabilitySetArgs args, InvokeOptions? options = null)
=> Pulumi.Deployment.Instance.InvokeAsync<GetAvailabilitySetResult>("azure-native:compute/v20171201:getAvailabilitySet", args ?? new GetAvailabilitySetArgs(), options.WithVersion());
}
public sealed class GetAvailabilitySetArgs : Pulumi.InvokeArgs
{
/// <summary>
/// The name of the availability set.
/// </summary>
[Input("availabilitySetName", required: true)]
public string AvailabilitySetName { get; set; } = null!;
/// <summary>
/// The name of the resource group.
/// </summary>
[Input("resourceGroupName", required: true)]
public string ResourceGroupName { get; set; } = null!;
public GetAvailabilitySetArgs()
{
}
}
[OutputType]
public sealed class GetAvailabilitySetResult
{
/// <summary>
/// Resource Id
/// </summary>
public readonly string Id;
/// <summary>
/// Resource location
/// </summary>
public readonly string Location;
/// <summary>
/// Resource name
/// </summary>
public readonly string Name;
/// <summary>
/// Fault Domain count.
/// </summary>
public readonly int? PlatformFaultDomainCount;
/// <summary>
/// Update Domain count.
/// </summary>
public readonly int? PlatformUpdateDomainCount;
/// <summary>
/// Sku of the availability set
/// </summary>
public readonly Outputs.SkuResponse? Sku;
/// <summary>
/// The resource status information.
/// </summary>
public readonly ImmutableArray<Outputs.InstanceViewStatusResponse> Statuses;
/// <summary>
/// Resource tags
/// </summary>
public readonly ImmutableDictionary<string, string>? Tags;
/// <summary>
/// Resource type
/// </summary>
public readonly string Type;
/// <summary>
/// A list of references to all virtual machines in the availability set.
/// </summary>
public readonly ImmutableArray<Outputs.SubResourceResponse> VirtualMachines;
[OutputConstructor]
private GetAvailabilitySetResult(
string id,
string location,
string name,
int? platformFaultDomainCount,
int? platformUpdateDomainCount,
Outputs.SkuResponse? sku,
ImmutableArray<Outputs.InstanceViewStatusResponse> statuses,
ImmutableDictionary<string, string>? tags,
string type,
ImmutableArray<Outputs.SubResourceResponse> virtualMachines)
{
Id = id;
Location = location;
Name = name;
PlatformFaultDomainCount = platformFaultDomainCount;
PlatformUpdateDomainCount = platformUpdateDomainCount;
Sku = sku;
Statuses = statuses;
Tags = tags;
Type = type;
VirtualMachines = virtualMachines;
}
}
}
| 37.669421 | 894 | 0.638219 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/Compute/V20171201/GetAvailabilitySet.cs | 4,558 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace NAudioDemo {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Images {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Images() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </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("NAudioDemo.Images", typeof(Images).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap Back {
get {
object obj = ResourceManager.GetObject("Back", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap Forward {
get {
object obj = ResourceManager.GetObject("Forward", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap Loop {
get {
object obj = ResourceManager.GetObject("Loop", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap Open {
get {
object obj = ResourceManager.GetObject("Open", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap Pause {
get {
object obj = ResourceManager.GetObject("Pause", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap Play {
get {
object obj = ResourceManager.GetObject("Play", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap Rewind {
get {
object obj = ResourceManager.GetObject("Rewind", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap Shuffle {
get {
object obj = ResourceManager.GetObject("Shuffle", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap Stop {
get {
object obj = ResourceManager.GetObject("Stop", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
}
}
| 39.006494 | 159 | 0.55735 | [
"MIT"
] | skor98/DtWPF | speechKit/NAudio-master/NAudioDemo/Images.Designer.cs | 6,009 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// La información general de un ensamblado se controla mediante el siguiente
// conjunto de atributos. Cambie estos valores de atributo para modificar la información
// asociada a un ensamblado.
[assembly: AssemblyTitle("metodos de ordenamiento")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("metodos de ordenamiento")]
[assembly: AssemblyCopyright("Copyright © 2020")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Si establece ComVisible en false, los tipos de este ensamblado no estarán visibles
// para los componentes COM. Si es necesario obtener acceso a un tipo en este ensamblado desde
// COM, establezca el atributo ComVisible en true en este tipo.
[assembly: ComVisible(false)]
// El siguiente GUID sirve como id. de typelib si este proyecto se expone a COM.
[assembly: Guid("14d1320b-1778-440e-985a-b12197e0afef")]
// La información de versión de un ensamblado consta de los cuatro valores siguientes:
//
// Versión principal
// Versión secundaria
// Número de compilación
// Revisión
//
// Puede especificar todos los valores o usar los valores predeterminados de número de compilación y de revisión
// utilizando el carácter "*", como se muestra a continuación:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 41.648649 | 112 | 0.758598 | [
"Apache-2.0"
] | josema471/ProgramacionIIIQCJM | practicas del primer parcial/unidad/metodos de ordenamiento/metodos de ordenamiento/Properties/AssemblyInfo.cs | 1,559 | C# |
using OdeToFood.Models;
using System.Collections.Generic;
namespace OdeToFood.ViewModels
{
public class HomeIndexViewModel
{
public IEnumerable<Restaurant> Restaurant { get; set; }
public string CurrentMessage { get; set; }
}
} | 23.272727 | 63 | 0.707031 | [
"MIT"
] | gilmoreg/learn | csharp/OdeToFood/ViewModels/HomeIndexViewModel.cs | 256 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RemGame
{
class DecisionResult : Decision
{
public bool Result { get; set; }
public String Action { get; set; }
public override string Evaluate(Enemy en)
{
return Action;
}
}
}
| 19.5 | 50 | 0.592308 | [
"MIT"
] | Benova11/REM | RemGame/Utils/DecisionResult.cs | 392 | C# |
using Furion.DependencyInjection;
using Microsoft.Extensions.Caching.Memory;
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Text;
using Yitter.IdGenerator;
namespace Xuey.NET.Framework
{
/// <summary>
/// 常规验证码
/// </summary>
public class GeneralCaptcha : IGeneralCaptcha, ITransient
{
private readonly IMemoryCache _memoryCache;
public GeneralCaptcha(IMemoryCache memoryCache)
{
_memoryCache = memoryCache;
}
/// <summary>
/// 生成验证码图片
/// </summary>
/// <param name="length"></param>
/// <returns></returns>
public dynamic CreateCaptchaImage(int length = 4)
{
var rtnResult = new ClickWordCaptchaResult();
var code = GenerateRandom(length); // 随机字符串集合
rtnResult.RepData.OriginalImageBase64 = Convert.ToBase64String(Draw(code)); //"data:image/jpg;base64," +
rtnResult.RepData.Token = YitIdHelper.NextId().ToString();
// 缓存验证码正确位置集合
var cacheOptions = new MemoryCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromSeconds(30));
_memoryCache.Set(CommonConst.CACHE_KEY_CODE + rtnResult.RepData.Token, code, cacheOptions);
rtnResult.RepData.Point = null; // 清空位置信息
return rtnResult;
}
private static byte[] Draw(string code)
{
int codeW = 110;
int codeH = 36;
int fontSize = 22;
// 颜色列表,用于验证码、噪线、噪点
Color[] color = { Color.Black, Color.Red, Color.Blue, Color.Green, Color.Orange, Color.Brown, Color.Brown, Color.DarkBlue };
// 字体列表,用于验证码
string[] fonts = new[] { "Times New Roman", "Verdana", "Arial", "Gungsuh", "Impact" };
using (var bmp = new Bitmap(codeW, codeH))
using (var g = Graphics.FromImage(bmp))
using (var ms = new MemoryStream())
{
g.Clear(Color.White);
var rnd = new Random();
// 画噪线
for (int i = 0; i < 1; i++)
{
int x1 = rnd.Next(codeW);
int y1 = rnd.Next(codeH);
int x2 = rnd.Next(codeW);
int y2 = rnd.Next(codeH);
var clr = color[rnd.Next(color.Length)];
g.DrawLine(new Pen(clr), x1, y1, x2, y2);
}
// 画验证码字符串
string fnt;
Font ft;
for (int i = 0; i < code.Length; i++)
{
fnt = fonts[rnd.Next(fonts.Length)];
ft = new Font(fnt, fontSize);
var clr = color[rnd.Next(color.Length)];
g.DrawString(code[i].ToString(), ft, new SolidBrush(clr), (float)i * 24 + 2, (float)0);
}
// 将验证码图片写入内存流
bmp.Save(ms, ImageFormat.Png);
return ms.ToArray();
}
}
private static string GenerateRandom(int length)
{
var chars = new StringBuilder();
// 验证码的字符集,去掉了一些容易混淆的字符
char[] character = { '2', '3', '4', '5', '6', '8', '9', 'a', 'b', 'd', 'e', 'f', 'h', 'k', 'm', 'n', 'r', 'x', 'y', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'R', 'S', 'T', 'W', 'X', 'Y' };
Random rnd = new();
// 生成验证码字符串
for (int i = 0; i < length; i++)
{
chars.Append(character[rnd.Next(character.Length)]);
}
return chars.ToString();
}
/// <summary>
/// 验证码验证
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public dynamic CheckCode(GeneralCaptchaInput input)
{
var res = new ClickWordCaptchaResult();
var code = _memoryCache.Get(CommonConst.CACHE_KEY_CODE + input.Token);
if (code == null)
{
res.RepCode = "6110";
res.RepMsg = "验证码已失效,请重新获取";
return res;
}
if (string.Compare(input.CaptchaCode, (string)code, true) != 0)
{
res.RepCode = "6112";
res.RepMsg = "验证码错误";
return res;
}
_memoryCache.Remove(CommonConst.CACHE_KEY_CODE + input.Token);
res.RepCode = "0000";
res.RepMsg = "验证成功";
return res;
}
}
} | 34.511278 | 229 | 0.486057 | [
"MIT"
] | xueynet/XYP | src/backend/Xuey.NET.Framework/Captcha/General/GeneralCaptcha.cs | 4,866 | C# |
using System;
using Microsoft.Rest;
using Microsoft.ServiceFabric.Services.Client;
using Microsoft.ServiceFabric.Services.Communication.Client;
namespace ServiceFabric.AutoRest.Communication.Client
{
public class RestServicePartitionClient<TClient> : ServicePartitionClient<RestCommunicationClient<TClient>>, IRestServicePartitionClient<TClient>
where TClient : ServiceClient<TClient>
{
public RestServicePartitionClient(
ICommunicationClientFactory<RestCommunicationClient<TClient>> communicationClientFactory,
Uri serviceUri,
ServicePartitionKey partitionKey = null,
TargetReplicaSelector targetReplicaSelector = TargetReplicaSelector.Default,
string listenerName = null,
OperationRetrySettings retrySettings = null)
: base(communicationClientFactory, serviceUri, partitionKey, targetReplicaSelector, listenerName, retrySettings)
{
if (communicationClientFactory == null) throw new ArgumentNullException(nameof(communicationClientFactory));
if (serviceUri == null) throw new ArgumentNullException(nameof(serviceUri));
}
}
}
| 47.36 | 149 | 0.744088 | [
"MIT"
] | mikanyg/ServiceFabric.AutoRest | Src/ServiceFabric.AutoRest.Communication/RestServicePartitionClient.cs | 1,186 | C# |
using System;
using System.Collections.Generic;
using System.Numerics;
using System.Reactive;
using System.Reactive.Subjects;
using System.Reflection;
using Veldrid.SceneGraph.VertexTypes;
namespace Veldrid.SceneGraph.Util.Shape
{
internal class PathGeometryBuilder<T> : GeometryBuilderBase<T> where T : struct, ISettablePrimitiveElement
{
internal void Build(IGeometry<T> geometry, ITessellationHints hints, Vector3[] colors, IPath path)
{
if (path.PathLocations.Length < 2)
{
throw new ArgumentException("Not enough vertices for a path");
}
if (hints.Radius < 0)
{
throw new ArgumentException("Negative radius is not valid");
}
if (System.Math.Abs(hints.Radius) < 1e-8)
{
BuildLine(geometry, hints, colors, path);
}
else
{
BuildCylinder(geometry, hints, colors, path);
}
}
private void BuildLine(IGeometry<T> geometry, ITessellationHints hints, Vector3[] colors, IPath path)
{
var vertexDataList = new List<T>();
var indexDataList = new List<uint>();
// Draw a line
for (var i = 0; i < path.PathLocations.Length; ++i)
{
var vtx = new T();
vtx.SetPosition(path.PathLocations[i]);
vtx.SetNormal(Vector3.UnitX);
vtx.SetTexCoord(Vector2.Zero);
vtx.SetColor3(colors[0]);
vertexDataList.Add(vtx);
indexDataList.Add((uint)i);
}
geometry.VertexData = vertexDataList.ToArray();
geometry.IndexData = indexDataList.ToArray();
geometry.VertexLayout = VertexLayoutHelpers.GetLayoutDescription(typeof(T));
var pSet = DrawElements<T>.Create(
geometry,
PrimitiveTopology.LineStrip,
(uint)geometry.IndexData.Length,
1,
0,
0,
0);
geometry.PrimitiveSets.Add(pSet);
}
private void BuildCylinder(IGeometry<T> geometry, ITessellationHints hints, Vector3[] colors, IPath path)
{
var tangents = Util.Math.ComputePathTangents(path.PathLocations);
var nSegments = (int)System.Math.Floor(10f * hints.DetailRatio);
if (nSegments < 4) nSegments = 4;
var shape = new Vector2[nSegments];
for (var i = 0; i < nSegments; ++i)
{
var theta = i * 2 * System.Math.PI / nSegments;
var r = hints.Radius;
shape[i] = new Vector2((float)(r*System.Math.Sin(theta)), (float)(r*System.Math.Cos(theta)));
}
var extrusion = Math.ExtrudeShape(shape, path.PathLocations);
// Build from quad strips
for (var j = 0; j < nSegments-1; ++j)
{
Begin();
BuildFromIndicies(j, j+1, extrusion, path);
End();
}
// Join the last bit...
BuildFromIndicies(nSegments-1, 0, extrusion, path);
BuildVertexAndIndexArrays(out var vertexArray, out var indexArray, colors);
geometry.VertexData = vertexArray;
geometry.IndexData = indexArray;
geometry.VertexLayout = VertexLayoutHelpers.GetLayoutDescription(typeof(T));
var pSet = DrawElements<T>.Create(
geometry,
PrimitiveTopology.TriangleList,
(uint)geometry.IndexData.Length,
1,
0,
0,
0);
geometry.PrimitiveSets.Add(pSet);
}
private void BuildFromIndicies(int a, int b, Vector3[,] extrusion, IPath path)
{
Begin();
for (var i = 0; i < path.PathLocations.Length-1; ++i)
{
// C1
var ctr0 = path.PathLocations[i];
var vtx0 = extrusion[i, b];
var nrm0 = Vector3.Normalize(Vector3.Subtract(vtx0, ctr0));
Vertex3f(vtx0);
Normal3f(nrm0);
TexCoord2f(1.0f, 0.0f);
// C2
var vtx1 = extrusion[i, a];
var nrm1 = Vector3.Normalize(Vector3.Subtract(vtx1, ctr0));
Vertex3f(vtx1);
Normal3f(nrm1);
TexCoord2f(1.0f, 0.0f);
// C3
var ctr1 = path.PathLocations[i+1];
var vtx2 = extrusion[i+1, b];
var nrm2 = Vector3.Normalize(Vector3.Subtract(vtx2, ctr1));
Vertex3f(vtx2);
Normal3f(nrm2);
TexCoord2f(1.0f, 0.0f);
// C4
var vtx3 = extrusion[i+1, a];
var nrm3 = Vector3.Normalize(Vector3.Subtract(vtx3, ctr1));
Vertex3f(vtx3);
Normal3f(nrm3);
TexCoord2f(1.0f, 0.0f);
}
End();
}
}
} | 33.584337 | 113 | 0.472646 | [
"Apache-2.0"
] | seanspicer/nexscenegraph | src/Veldrid.SceneGraph/Util/Shape/PathGeometryBuilder.cs | 5,575 | C# |
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;
using HTTPnet.Core.Communication;
using HTTPnet.Core.Http;
namespace HTTPnet.Implementations
{
public class ServerSocketWrapper : IServerSocketWrapper
{
private readonly HttpServerOptions _options;
private Socket _listener;
public ServerSocketWrapper(HttpServerOptions options)
{
_options = options ?? throw new ArgumentNullException(nameof(options));
}
public Task StartAsync()
{
if (_listener != null)
{
throw new InvalidOperationException("Already started.");
}
_listener = new Socket(SocketType.Stream, ProtocolType.Tcp)
{
NoDelay = _options.NoDelay
};
_listener.Bind(new IPEndPoint(IPAddress.Any, _options.Port));
_listener.Listen(_options.Backlog);
return Task.FromResult(0);
}
public Task StopAsync()
{
if (_listener == null)
{
return Task.FromResult(0);
}
_listener.Shutdown(SocketShutdown.Both);
_listener.Dispose();
_listener = null;
return Task.FromResult(0);
}
public void Dispose()
{
_listener?.Shutdown(SocketShutdown.Both);
_listener?.Dispose();
_listener = null;
}
public async Task<IClientSocketWrapper> AcceptAsync()
{
#if (WINDOWS_UWP)
var clientSocket = await _listener.AcceptAsync();
#else
var clientSocket = await Task.Factory.FromAsync(_listener.BeginAccept, _listener.EndAccept, null).ConfigureAwait(false);
#endif
clientSocket.NoDelay = _options.NoDelay;
return new ClientSocketWrapper(clientSocket);
}
}
}
| 26.726027 | 132 | 0.577652 | [
"MIT"
] | chkr1011/HTTPnet | Frameworks/HTTPnet.UniversalWindows/Implementations/ServerSocketWrapper.cs | 1,953 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MVCDemo.IBLL
{
/// <summary>
/// 接口基类
/// </summary>
/// <typeparam name="T">类型</typeparam>
public interface InterfaceBaseService<T> where T :class
{
/// <summary>
/// 添加
/// </summary>
/// <param name="entity">数据实体</param>
/// <returns>添加后的数据实体</returns>
T Add(T entity);
/// <summary>
/// 查找数据
/// </summary>
/// <param name="entity">主键</param>
/// <returns>实体</returns>
T Find(int ID);
/// <summary>
/// 更新
/// </summary>
/// <param name="entity">数据实体</param>
/// <returns>是否成功</returns>
bool Update(T entity);
/// <summary>
/// 删除
/// </summary>
/// <param name="entity">数据实体</param>
/// <returns>是否成功</returns>
bool Delete(T entity);
/// <summary>
/// 获取指定页数据
/// </summary>
/// <param name="entitys">数据实体集</param>
/// <param name="pageIndex">页码</param>
/// <param name="pageSize">页记录数</param>
/// <returns></returns>
IQueryable<T> PageList(IQueryable<T> entitys, int pageIndex, int pageSize);
}
}
| 26.836735 | 83 | 0.506464 | [
"MIT"
] | kuaidaoyanglang/MvcDemo | MVCDemo.IBLL/InterfaceBaseService.cs | 1,449 | C# |
namespace Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210
{
using Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.PowerShell;
/// <summary>
/// A PowerShell PSTypeConverter to support converting to an instance of <see cref="PushInstallerDetails" />
/// </summary>
public partial class PushInstallerDetailsTypeConverter : global::System.Management.Automation.PSTypeConverter
{
/// <summary>
/// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" />
/// parameter.
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <returns>
/// <c>true</c> if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" />
/// parameter, otherwise <c>false</c>.
/// </returns>
public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue);
/// <summary>
/// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" />
/// parameter.
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object" /> instance to check if it can be converted to the <see cref="PushInstallerDetails"
/// /> type.</param>
/// <returns>
/// <c>true</c> if the instance could be converted to a <see cref="PushInstallerDetails" /> type, otherwise <c>false</c>
/// </returns>
public static bool CanConvertFrom(dynamic sourceValue)
{
if (null == sourceValue)
{
return true;
}
global::System.Type type = sourceValue.GetType();
if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type))
{
// we say yest to PSObjects
return true;
}
if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type))
{
// we say yest to Hashtables/dictionaries
return true;
}
try
{
if (null != sourceValue.ToJsonString())
{
return true;
}
}
catch
{
// Not one of our objects
}
try
{
string text = sourceValue.ToString()?.Trim();
return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonType.Object;
}
catch
{
// Doesn't look like it can be treated as JSON
}
return false;
}
/// <summary>
/// Determines if the <see cref="sourceValue" /> parameter can be converted to the <see cref="destinationType" /> parameter
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <returns>
/// <c>true</c> if the converter can convert the <see cref="sourceValue" /> parameter to the <see cref="destinationType" />
/// parameter, otherwise <c>false</c>
/// </returns>
public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false;
/// <summary>
/// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider"
/// /> and <see cref="ignoreCase" />
/// </summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <param name="formatProvider">not used by this TypeConverter.</param>
/// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param>
/// <returns>
/// an instance of <see cref="PushInstallerDetails" />, or <c>null</c> if there is no suitable conversion.
/// </returns>
public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue);
/// <summary>
/// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider"
/// /> and <see cref="ignoreCase" />
/// </summary>
/// <param name="sourceValue">the value to convert into an instance of <see cref="PushInstallerDetails" />.</param>
/// <returns>
/// an instance of <see cref="PushInstallerDetails" />, or <c>null</c> if there is no suitable conversion.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IPushInstallerDetails ConvertFrom(dynamic sourceValue)
{
if (null == sourceValue)
{
return null;
}
global::System.Type type = sourceValue.GetType();
if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IPushInstallerDetails).IsAssignableFrom(type))
{
return sourceValue;
}
try
{
return PushInstallerDetails.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());;
}
catch
{
// Unable to use JSON pattern
}
if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type))
{
return PushInstallerDetails.DeserializeFromPSObject(sourceValue);
}
if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type))
{
return PushInstallerDetails.DeserializeFromDictionary(sourceValue);
}
return null;
}
/// <summary>NotImplemented -- this will return <c>null</c></summary>
/// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
/// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
/// <param name="formatProvider">not used by this TypeConverter.</param>
/// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param>
/// <returns>will always return <c>null</c>.</returns>
public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null;
}
} | 51.661972 | 245 | 0.584378 | [
"MIT"
] | AverageDesigner/azure-powershell | src/Migrate/generated/api/Models/Api20210210/PushInstallerDetails.TypeConverter.cs | 7,195 | C# |
//
// AssemblyInfo.cs
//
// Author:
// Matt Ward <matt.ward@microsoft.com>
//
// Copyright (c) 2017 Microsoft
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle ("LanguageServer")]
[assembly: AssemblyDescription ("")]
[assembly: AssemblyConfiguration ("")]
[assembly: AssemblyCompany ("")]
[assembly: AssemblyProduct ("")]
[assembly: AssemblyCopyright ("Microsoft")]
[assembly: AssemblyTrademark ("")]
[assembly: AssemblyCulture ("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion ("0.1")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
| 42.057692 | 82 | 0.747142 | [
"MIT"
] | mrward/monodevelop-language-server-addin | src/LanguageServerLibrary/Properties/AssemblyInfo.cs | 2,189 | C# |
using FSNEP.BLL.Impl;
using FSNEP.Core.Abstractions;
using FSNEP.Core.Domain;
namespace FSNEP.BLL.Interfaces
{
public interface IReportBLL
{
ReportResult GenerateIndividualTimeRecordReport(TimeRecord timeRecord, ReportType reportType);
ReportResult GenerateCostShare(Project project, int year, ReportType reportType);
}
} | 30.083333 | 103 | 0.750693 | [
"MIT"
] | ucdavis/FSNEP | FSNEP.BLL/Interfaces/IReportBLL.cs | 361 | C# |
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Xml.Linq;
using Microsoft.VisualBasic;
using Microsoft.VisualBasic.CompilerServices;
// 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.
// See Compiler::LoadXmlSolutionExtension
namespace VbNetStandardLib.My
{
[Embedded()]
[DebuggerNonUserCode()]
[System.Runtime.CompilerServices.CompilerGenerated()]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
internal sealed class InternalXmlHelper
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
private InternalXmlHelper()
{
}
public static string get_Value(IEnumerable<XElement> source)
{
foreach (XElement item in source)
return item.Value;
return null;
}
public static void set_Value(IEnumerable<XElement> source, string value)
{
foreach (XElement item in source)
{
item.Value = value;
break;
}
}
public static string get_AttributeValue(IEnumerable<XElement> source, XName name)
{
foreach (XElement item in source)
return Conversions.ToString(item.Attribute(name));
return null;
}
public static void set_AttributeValue(IEnumerable<XElement> source, XName name, string value)
{
foreach (XElement item in source)
{
item.SetAttributeValue(name, value);
break;
}
}
public static string get_AttributeValue(XElement source, XName name)
{
return Conversions.ToString(source.Attribute(name));
}
public static void set_AttributeValue(XElement source, XName name, string value)
{
source.SetAttributeValue(name, value);
}
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public static XAttribute CreateAttribute(XName name, object value)
{
if (value is null)
{
return null;
}
return new XAttribute(name, value);
}
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public static XAttribute CreateNamespaceAttribute(XName name, XNamespace ns)
{
var a = new XAttribute(name, ns.NamespaceName);
a.AddAnnotation(ns);
return a;
}
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public static object RemoveNamespaceAttributes(string[] inScopePrefixes, XNamespace[] inScopeNs, List<XAttribute> attributes, object obj)
{
if (obj is not null)
{
XElement elem = obj as XElement;
if (elem is not null)
{
return RemoveNamespaceAttributes(inScopePrefixes, inScopeNs, attributes, elem);
}
else
{
IEnumerable elems = obj as IEnumerable;
if (elems is not null)
{
return RemoveNamespaceAttributes(inScopePrefixes, inScopeNs, attributes, elems);
}
}
}
return obj;
}
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public static IEnumerable RemoveNamespaceAttributes(string[] inScopePrefixes, XNamespace[] inScopeNs, List<XAttribute> attributes, IEnumerable obj)
{
if (obj is not null)
{
IEnumerable<XElement> elems = obj as IEnumerable<XElement>;
if (elems is not null)
{
return elems.Select(new RemoveNamespaceAttributesClosure(inScopePrefixes, inScopeNs, attributes).ProcessXElement);
}
else
{
return obj.Cast<object>().Select(new RemoveNamespaceAttributesClosure(inScopePrefixes, inScopeNs, attributes).ProcessObject);
}
}
return obj;
}
[DebuggerNonUserCode()]
[System.Runtime.CompilerServices.CompilerGenerated()]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
private sealed class RemoveNamespaceAttributesClosure
{
private readonly string[] m_inScopePrefixes;
private readonly XNamespace[] m_inScopeNs;
private readonly List<XAttribute> m_attributes;
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
internal RemoveNamespaceAttributesClosure(string[] inScopePrefixes, XNamespace[] inScopeNs, List<XAttribute> attributes)
{
m_inScopePrefixes = inScopePrefixes;
m_inScopeNs = inScopeNs;
m_attributes = attributes;
}
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
internal XElement ProcessXElement(XElement elem)
{
return RemoveNamespaceAttributes(m_inScopePrefixes, m_inScopeNs, m_attributes, elem);
}
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
internal object ProcessObject(object obj)
{
XElement elem = obj as XElement;
if (elem is not null)
{
return RemoveNamespaceAttributes(m_inScopePrefixes, m_inScopeNs, m_attributes, elem);
}
else
{
return obj;
}
}
}
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public static XElement RemoveNamespaceAttributes(string[] inScopePrefixes, XNamespace[] inScopeNs, List<XAttribute> attributes, XElement e)
{
if (e is not null)
{
var a = e.FirstAttribute;
while (a is not null)
{
var nextA = a.NextAttribute;
if (a.IsNamespaceDeclaration)
{
var ns = a.Annotation<XNamespace>();
string prefix = a.Name.LocalName;
if (ns is not null)
{
if (inScopePrefixes is not null && inScopeNs is not null)
{
int lastIndex = inScopePrefixes.Length - 1;
for (int i = 0, loopTo = lastIndex; i <= loopTo; i++)
{
string currentInScopePrefix = inScopePrefixes[i];
var currentInScopeNs = inScopeNs[i];
if (prefix.Equals(currentInScopePrefix))
{
if (ns == currentInScopeNs)
{
// prefix and namespace match. Remove the unneeded ns attribute
a.Remove();
}
// prefix is in scope but refers to something else. Leave the ns attribute.
a = null;
break;
}
}
}
if (a is not null)
{
// Prefix is not in scope
// Now check whether it's going to be in scope because it is in the attributes list
if (attributes is not null)
{
int lastIndex = attributes.Count - 1;
for (int i = 0, loopTo1 = lastIndex; i <= loopTo1; i++)
{
var currentA = attributes[i];
string currentInScopePrefix = currentA.Name.LocalName;
var currentInScopeNs = currentA.Annotation<XNamespace>();
if (currentInScopeNs is not null)
{
if (prefix.Equals(currentInScopePrefix))
{
if (ns == currentInScopeNs)
{
// prefix and namespace match. Remove the unneeded ns attribute
a.Remove();
}
// prefix is in scope but refers to something else. Leave the ns attribute.
a = null;
break;
}
}
}
}
if (a is not null)
{
// Prefix is definitely not in scope
a.Remove();
// namespace is not defined either. Add this attributes list
attributes.Add(a);
}
}
}
}
a = nextA;
}
}
return e;
}
}
} | 44.417355 | 156 | 0.472881 | [
"MIT"
] | BingCheng21/CodeConverter | Tests/TestData/MultiFileCharacterization/VBToCSResults/ConvertWholeSolution/VbNetStandardLib/My Project/MyNamespace.Static.3.Designer.cs | 10,508 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[ExecuteInEditMode]
public class EnviroCloudsAnimateWithTime : MonoBehaviour {
void Update ()
{
if(EnviroSky.instance == null)
return;
float timeToAnimation = EnviroSky.instance.Remap(EnviroSky.instance.GetTimeOfDay(),0f,24f,-1f,1f);
float timeOfYearInHours = EnviroSky.instance.GetTimeOfDay() + (EnviroSky.instance.GameTime.Days * 24f);
EnviroSky.instance.cloudAnim = new Vector3(timeToAnimation * EnviroSky.instance.cloudsSettings.cloudsWindDirectionX,timeToAnimation * -1f,timeToAnimation * EnviroSky.instance.cloudsSettings.cloudsWindDirectionY);
EnviroSky.instance.cloudAnimNonScaled = new Vector2(timeOfYearInHours * EnviroSky.instance.cloudsSettings.cloudsWindDirectionX,timeOfYearInHours * EnviroSky.instance.cloudsSettings.cloudsWindDirectionY);
}
}
| 41.095238 | 214 | 0.8146 | [
"Unlicense"
] | adityawahyu04/Tugas-Pertemuan-1-Lab-Pemgame | Assets/Enviro - Sky and Weather/Enviro Standard/Scripts/Utilities/EnviroCloudsAnimateWithTime.cs | 865 | C# |
// c:\program files (x86)\windows kits\10\include\10.0.22000.0\um\mmsyscom.h(110,5)
using System;
using System.Runtime.InteropServices;
namespace DirectN
{
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public partial struct mmtime_tag__union_0
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public byte[] __bits;
public uint ms { get => InteropRuntime.GetUInt32(__bits, 0, 32); set { if (__bits == null) __bits = new byte[8]; InteropRuntime.SetUInt32(value, __bits, 0, 32); } }
public uint sample { get => InteropRuntime.GetUInt32(__bits, 0, 32); set { if (__bits == null) __bits = new byte[8]; InteropRuntime.SetUInt32(value, __bits, 0, 32); } }
public uint cb { get => InteropRuntime.GetUInt32(__bits, 0, 32); set { if (__bits == null) __bits = new byte[8]; InteropRuntime.SetUInt32(value, __bits, 0, 32); } }
public uint ticks { get => InteropRuntime.GetUInt32(__bits, 0, 32); set { if (__bits == null) __bits = new byte[8]; InteropRuntime.SetUInt32(value, __bits, 0, 32); } }
public mmtime_tag__union_0__struct_0 smpte { get => InteropRuntime.Get<mmtime_tag__union_0__struct_0>(__bits, 0, 64); set { if (__bits == null) __bits = new byte[8]; InteropRuntime.Set<mmtime_tag__union_0__struct_0>(value, __bits, 0, 64); } }
public mmtime_tag__union_0__struct_1 midi { get => InteropRuntime.Get<mmtime_tag__union_0__struct_1>(__bits, 0, 32); set { if (__bits == null) __bits = new byte[8]; InteropRuntime.Set<mmtime_tag__union_0__struct_1>(value, __bits, 0, 32); } }
}
}
| 79.952381 | 251 | 0.693865 | [
"MIT"
] | Steph55/DirectN | DirectN/DirectN/Generated/mmtime_tag__union_0.cs | 1,681 | C# |
using System.Threading.Tasks;
using TwoContexts.Configuration.Dto;
namespace TwoContexts.Configuration
{
public interface IConfigurationAppService
{
Task ChangeUiTheme(ChangeUiThemeInput input);
}
}
| 20.090909 | 53 | 0.764706 | [
"MIT"
] | BertusVanZyl/MultipleContext | src/TwoContexts.Application/Configuration/IConfigurationAppService.cs | 223 | C# |
using Abp.Authorization;
using Abp.Configuration.Startup;
using Abp.Localization;
using Abp.MultiTenancy;
namespace Afonsoft.SetBox.Authorization
{
/// <summary>
/// Application's authorization provider.
/// Defines permissions for the application.
/// See <see cref="AppPermissions"/> for all permission names.
/// </summary>
public class AppAuthorizationProvider : AuthorizationProvider
{
private readonly bool _isMultiTenancyEnabled;
public AppAuthorizationProvider(bool isMultiTenancyEnabled)
{
_isMultiTenancyEnabled = isMultiTenancyEnabled;
}
public AppAuthorizationProvider(IMultiTenancyConfig multiTenancyConfig)
{
_isMultiTenancyEnabled = multiTenancyConfig.IsEnabled;
}
public override void SetPermissions(IPermissionDefinitionContext context)
{
//COMMON PERMISSIONS (FOR BOTH OF TENANTS AND HOST)
var pages = context.GetPermissionOrNull(AppPermissions.Pages) ?? context.CreatePermission(AppPermissions.Pages, L("Pages"));
pages.CreateChildPermission(AppPermissions.Pages_DemoUiComponents, L("DemoUiComponents"));
var administration = pages.CreateChildPermission(AppPermissions.Pages_Administration, L("Administration"));
var roles = administration.CreateChildPermission(AppPermissions.Pages_Administration_Roles, L("Roles"));
roles.CreateChildPermission(AppPermissions.Pages_Administration_Roles_Create, L("CreatingNewRole"));
roles.CreateChildPermission(AppPermissions.Pages_Administration_Roles_Edit, L("EditingRole"));
roles.CreateChildPermission(AppPermissions.Pages_Administration_Roles_Delete, L("DeletingRole"));
var users = administration.CreateChildPermission(AppPermissions.Pages_Administration_Users, L("Users"));
users.CreateChildPermission(AppPermissions.Pages_Administration_Users_Create, L("CreatingNewUser"));
users.CreateChildPermission(AppPermissions.Pages_Administration_Users_Edit, L("EditingUser"));
users.CreateChildPermission(AppPermissions.Pages_Administration_Users_Delete, L("DeletingUser"));
users.CreateChildPermission(AppPermissions.Pages_Administration_Users_ChangePermissions, L("ChangingPermissions"));
users.CreateChildPermission(AppPermissions.Pages_Administration_Users_Impersonation, L("LoginForUsers"));
users.CreateChildPermission(AppPermissions.Pages_Administration_Users_Unlock, L("Unlock"));
var languages = administration.CreateChildPermission(AppPermissions.Pages_Administration_Languages, L("Languages"));
languages.CreateChildPermission(AppPermissions.Pages_Administration_Languages_Create, L("CreatingNewLanguage"));
languages.CreateChildPermission(AppPermissions.Pages_Administration_Languages_Edit, L("EditingLanguage"));
languages.CreateChildPermission(AppPermissions.Pages_Administration_Languages_Delete, L("DeletingLanguages"));
languages.CreateChildPermission(AppPermissions.Pages_Administration_Languages_ChangeTexts, L("ChangingTexts"));
administration.CreateChildPermission(AppPermissions.Pages_Administration_AuditLogs, L("AuditLogs"));
var organizationUnits = administration.CreateChildPermission(AppPermissions.Pages_Administration_OrganizationUnits, L("OrganizationUnits"));
organizationUnits.CreateChildPermission(AppPermissions.Pages_Administration_OrganizationUnits_ManageOrganizationTree, L("ManagingOrganizationTree"));
organizationUnits.CreateChildPermission(AppPermissions.Pages_Administration_OrganizationUnits_ManageMembers, L("ManagingMembers"));
organizationUnits.CreateChildPermission(AppPermissions.Pages_Administration_OrganizationUnits_ManageRoles, L("ManagingRoles"));
administration.CreateChildPermission(AppPermissions.Pages_Administration_UiCustomization, L("VisualSettings"));
//TENANT-SPECIFIC PERMISSIONS
pages.CreateChildPermission(AppPermissions.Pages_Tenant_Dashboard, L("Dashboard"), multiTenancySides: MultiTenancySides.Tenant);
administration.CreateChildPermission(AppPermissions.Pages_Administration_Tenant_Settings, L("Settings"), multiTenancySides: MultiTenancySides.Tenant);
administration.CreateChildPermission(AppPermissions.Pages_Administration_Tenant_SubscriptionManagement, L("Subscription"), multiTenancySides: MultiTenancySides.Tenant);
//HOST-SPECIFIC PERMISSIONS
var editions = pages.CreateChildPermission(AppPermissions.Pages_Editions, L("Editions"), multiTenancySides: MultiTenancySides.Host);
editions.CreateChildPermission(AppPermissions.Pages_Editions_Create, L("CreatingNewEdition"), multiTenancySides: MultiTenancySides.Host);
editions.CreateChildPermission(AppPermissions.Pages_Editions_Edit, L("EditingEdition"), multiTenancySides: MultiTenancySides.Host);
editions.CreateChildPermission(AppPermissions.Pages_Editions_Delete, L("DeletingEdition"), multiTenancySides: MultiTenancySides.Host);
editions.CreateChildPermission(AppPermissions.Pages_Editions_MoveTenantsToAnotherEdition, L("MoveTenantsToAnotherEdition"), multiTenancySides: MultiTenancySides.Host);
var tenants = pages.CreateChildPermission(AppPermissions.Pages_Tenants, L("Tenants"), multiTenancySides: MultiTenancySides.Host);
tenants.CreateChildPermission(AppPermissions.Pages_Tenants_Create, L("CreatingNewTenant"), multiTenancySides: MultiTenancySides.Host);
tenants.CreateChildPermission(AppPermissions.Pages_Tenants_Edit, L("EditingTenant"), multiTenancySides: MultiTenancySides.Host);
tenants.CreateChildPermission(AppPermissions.Pages_Tenants_ChangeFeatures, L("ChangingFeatures"), multiTenancySides: MultiTenancySides.Host);
tenants.CreateChildPermission(AppPermissions.Pages_Tenants_Delete, L("DeletingTenant"), multiTenancySides: MultiTenancySides.Host);
tenants.CreateChildPermission(AppPermissions.Pages_Tenants_Impersonation, L("LoginForTenants"), multiTenancySides: MultiTenancySides.Host);
administration.CreateChildPermission(AppPermissions.Pages_Administration_Host_Settings, L("Settings"), multiTenancySides: MultiTenancySides.Host);
administration.CreateChildPermission(AppPermissions.Pages_Administration_Host_Maintenance, L("Maintenance"), multiTenancySides: _isMultiTenancyEnabled ? MultiTenancySides.Host : MultiTenancySides.Tenant);
administration.CreateChildPermission(AppPermissions.Pages_Administration_HangfireDashboard, L("HangfireDashboard"), multiTenancySides: _isMultiTenancyEnabled ? MultiTenancySides.Host : MultiTenancySides.Tenant);
administration.CreateChildPermission(AppPermissions.Pages_Administration_Host_Dashboard, L("Dashboard"), multiTenancySides: MultiTenancySides.Host);
//SETBOX PERMISSIONS
pages.CreateChildPermission(AppPermissions.Pages_Administration_SetBox, L("SetBox"));
}
private static ILocalizableString L(string name)
{
return new LocalizableString(name, SetBoxConsts.LocalizationSourceName);
}
}
}
| 71.696078 | 223 | 0.778203 | [
"Apache-2.0"
] | afonsoft/SetBox-VideoPlayer | SetBoxWebUI_New/src/Afonsoft.SetBox.Core/Authorization/AppAuthorizationProvider.cs | 7,315 | C# |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Game.Rulesets.Objects.Types;
namespace osu.Game.Rulesets.Osu.Objects.Drawables
{
public class DrawableSliderHead : DrawableHitCircle
{
private readonly IBindable<int> pathVersion = new Bindable<int>();
protected override OsuSkinComponents CirclePieceComponent => OsuSkinComponents.SliderHeadHitCircle;
private readonly Slider slider;
public DrawableSliderHead(Slider slider, SliderHeadCircle h)
: base(h)
{
this.slider = slider;
}
[BackgroundDependencyLoader]
private void load()
{
pathVersion.BindTo(slider.Path.Version);
PositionBindable.BindValueChanged(_ => updatePosition());
pathVersion.BindValueChanged(_ => updatePosition(), true);
}
protected override void Update()
{
base.Update();
double completionProgress = Math.Clamp((Time.Current - slider.StartTime) / slider.Duration, 0, 1);
//todo: we probably want to reconsider this before adding scoring, but it looks and feels nice.
if (!IsHit)
Position = slider.CurvePositionAt(completionProgress);
}
public Action<double> OnShake;
protected override void Shake(double maximumLength) => OnShake?.Invoke(maximumLength);
private void updatePosition() => Position = HitObject.Position - slider.Position;
}
}
| 33.173077 | 111 | 0.642319 | [
"MIT"
] | LeviCline/osu | osu.Game.Rulesets.Osu/Objects/Drawables/DrawableSliderHead.cs | 1,676 | 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 ecs-2014-11-13.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.ECS.Model
{
/// <summary>
/// Container for the parameters to the DeleteService operation.
/// Deletes a specified service within a cluster. You can delete a service if you have
/// no running tasks in it and the desired task count is zero. If the service is actively
/// maintaining tasks, you cannot delete it, and you must update the service to a desired
/// task count of zero. For more information, see <a>UpdateService</a>.
///
/// <note>
/// <para>
/// When you delete a service, if there are still running tasks that require cleanup,
/// the service status moves from <code>ACTIVE</code> to <code>DRAINING</code>, and the
/// service is no longer visible in the console or in the <a>ListServices</a> API operation.
/// After all tasks have transitioned to either <code>STOPPING</code> or <code>STOPPED</code>
/// status, the service status moves from <code>DRAINING</code> to <code>INACTIVE</code>.
/// Services in the <code>DRAINING</code> or <code>INACTIVE</code> status can still be
/// viewed with the <a>DescribeServices</a> API operation. However, in the future, <code>INACTIVE</code>
/// services may be cleaned up and purged from Amazon ECS record keeping, and <a>DescribeServices</a>
/// calls on those services return a <code>ServiceNotFoundException</code> error.
/// </para>
/// </note> <important>
/// <para>
/// If you attempt to create a new service with the same name as an existing service in
/// either <code>ACTIVE</code> or <code>DRAINING</code> status, you receive an error.
/// </para>
/// </important>
/// </summary>
public partial class DeleteServiceRequest : AmazonECSRequest
{
private string _cluster;
private bool? _force;
private string _service;
/// <summary>
/// Gets and sets the property Cluster.
/// <para>
/// The short name or full Amazon Resource Name (ARN) of the cluster that hosts the service
/// to delete. If you do not specify a cluster, the default cluster is assumed.
/// </para>
/// </summary>
public string Cluster
{
get { return this._cluster; }
set { this._cluster = value; }
}
// Check to see if Cluster property is set
internal bool IsSetCluster()
{
return this._cluster != null;
}
/// <summary>
/// Gets and sets the property Force.
/// <para>
/// If <code>true</code>, allows you to delete a service even if it has not been scaled
/// down to zero tasks. It is only necessary to use this if the service is using the <code>REPLICA</code>
/// scheduling strategy.
/// </para>
/// </summary>
public bool Force
{
get { return this._force.GetValueOrDefault(); }
set { this._force = value; }
}
// Check to see if Force property is set
internal bool IsSetForce()
{
return this._force.HasValue;
}
/// <summary>
/// Gets and sets the property Service.
/// <para>
/// The name of the service to delete.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public string Service
{
get { return this._service; }
set { this._service = value; }
}
// Check to see if Service property is set
internal bool IsSetService()
{
return this._service != null;
}
}
} | 37.942623 | 114 | 0.605746 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/ECS/Generated/Model/DeleteServiceRequest.cs | 4,629 | C# |
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.SqlTools.ServiceLayer.Test.Common;
using Microsoft.SqlTools.Utility;
using NUnit.Framework;
namespace Microsoft.SqlTools.ServiceLayer.UnitTests.ServiceHost
{
/// <summary>
/// Logger test cases
/// </summary>
public class LoggerTests
{
/// <summary>
/// Test to verify that the logger initialization is generating a valid file
/// Verifies that a test log entries is succesfully written to a default log file.
/// </summary>
[Test]
public void LoggerDefaultFile()
{
TestLogger test = new TestLogger()
{
TraceSource = MethodInfo.GetCurrentMethod().Name,
EventType = TraceEventType.Information,
TracingLevel = SourceLevels.Verbose,
};
test.Initialize();
test.Write();
test.Verify();
test.Cleanup();
}
/// <summary>
/// Test to verify that the logger initialization works using various possibilities.
/// </summary>
[Test]
public void LoggerTestInitialization()
{
int? testNo = 1;
//Test 1: Initialization with all defaults. Logfile names get autogenerated with the well known prefix.
{
SourceLevels expectedTracingLevel = Logger.defaultTracingLevel;
string expectedTraceSource = Logger.defaultTraceSource;
Logger.Initialize();
bool isLogFileExpectedToExist = ((uint)expectedTracingLevel >= (uint)SourceLevels.Information);
TestLogger.VerifyInitialization(expectedTracingLevel, expectedTraceSource, Logger.LogFileFullPath, isLogFileExpectedToExist, testNo++);
TestLogger.Cleanup(Logger.LogFileFullPath);
}
//Test 2: Initialization with TracingLevel set to Critical. Logfile names get autogenerated with the well known prefix. Before we do a write at Critical level the logfile must not get even created.
{
SourceLevels expectedTracingLevel = SourceLevels.Critical;
string expectedTraceSource = Logger.defaultTraceSource;
Logger.Initialize(expectedTracingLevel);
bool isLogFileExpectedToExist = ((uint)expectedTracingLevel >= (uint)SourceLevels.Information);
TestLogger.VerifyInitialization(expectedTracingLevel, expectedTraceSource, Logger.LogFileFullPath, isLogFileExpectedToExist, testNo++);
TestLogger.Cleanup(Logger.LogFileFullPath);
}
//Test 3: Initialization with TraceSourceName set to specified name. Logfile names get autogenerated with the well known prefix.
{
SourceLevels expectedTracingLevel = Logger.defaultTracingLevel;
string expectedTraceSource = nameof(LoggerTestInitialization);
Logger.Initialize(traceSource:expectedTraceSource);
bool isLogFileExpectedToExist = ((uint)expectedTracingLevel >= (uint)SourceLevels.Information);
TestLogger.VerifyInitialization(expectedTracingLevel, expectedTraceSource, Logger.LogFileFullPath, isLogFileExpectedToExist, testNo++);
TestLogger.Cleanup(Logger.LogFileFullPath);
}
//Test 4: Initialization with logfile set to specified random filepath.
{
SourceLevels expectedTracingLevel = Logger.defaultTracingLevel;
string expectedTraceSource = Logger.defaultTraceSource;
string logFilePath = Path.Combine(Path.GetRandomFileName(), nameof(LoggerTestInitialization));
Logger.Initialize(traceSource: expectedTraceSource, logFilePath: logFilePath);
Assert.True(string.Compare(logFilePath, Logger.LogFileFullPath, ignoreCase: true) == 0, "The logfile path of the Logger should be the one specified");
bool isLogFileExpectedToExist = ((uint)expectedTracingLevel >= (uint)SourceLevels.Information);
TestLogger.VerifyInitialization(expectedTracingLevel, expectedTraceSource, logFilePath, isLogFileExpectedToExist, testNo++);
TestLogger.Cleanup(Logger.LogFileFullPath);
}
//Test 5: Initialization with logfile generated from log directory and LogFilePrefix using Logger.GenerateLogFielPath method.
{
SourceLevels expectedTracingLevel = Logger.defaultTracingLevel;
string expectedTraceSource = Logger.defaultTraceSource;
string logFilePath = Logger.GenerateLogFilePath(Path.Combine(Directory.GetCurrentDirectory(), nameof(LoggerTestInitialization)));
Assert.True(string.Compare(Path.GetDirectoryName(logFilePath), Directory.GetCurrentDirectory(), ignoreCase: true) == 0, "The directory path of the logfile should match the directory path specified");
Logger.Initialize(traceSource: expectedTraceSource, logFilePath: logFilePath);
Assert.True(string.Compare(logFilePath, Logger.LogFileFullPath, ignoreCase: true) == 0, "The logfile path of the Logger should be the one specified");
bool isLogFileExpectedToExist = ((uint)expectedTracingLevel >= (uint)SourceLevels.Information);
TestLogger.VerifyInitialization(expectedTracingLevel, expectedTraceSource, Logger.LogFileFullPath, isLogFileExpectedToExist, testNo++);
TestLogger.Cleanup(Logger.LogFileFullPath);
}
#region TracingLevel Settings
//Test 6: Initialization tracingLevel specified as a null string.
{
string tracingLevel = null;
SourceLevels expectedTracingLevel = Logger.defaultTracingLevel;
string expectedTraceSource = Logger.defaultTraceSource;
Logger.Initialize(tracingLevel);
bool isLogFileExpectedToExist = false;
TestLogger.VerifyInitialization(expectedTracingLevel, expectedTraceSource, Logger.LogFileFullPath, isLogFileExpectedToExist, testNo++);
TestLogger.Cleanup(Logger.LogFileFullPath);
}
//Test 7: Initialization tracingLevel specified as an empty string.
{
string tracingLevel = null;
SourceLevels expectedTracingLevel = Logger.defaultTracingLevel;
string expectedTraceSource = Logger.defaultTraceSource;
Logger.Initialize(tracingLevel);
bool isLogFileExpectedToExist = false;
TestLogger.VerifyInitialization(expectedTracingLevel, expectedTraceSource, Logger.LogFileFullPath, isLogFileExpectedToExist, testNo++);
TestLogger.Cleanup(Logger.LogFileFullPath);
}
//Test 8: Initialization tracingLevel specified as an invalid string.
{
string tracingLevel = "invalid";
SourceLevels expectedTracingLevel = Logger.defaultTracingLevel;
string expectedTraceSource = Logger.defaultTraceSource;
Logger.Initialize(tracingLevel);
bool isLogFileExpectedToExist = false;
TestLogger.VerifyInitialization(expectedTracingLevel, expectedTraceSource, Logger.LogFileFullPath, isLogFileExpectedToExist, testNo++);
TestLogger.Cleanup(Logger.LogFileFullPath);
}
//Test 9: Initialization with logfile set to empty string.
{
SourceLevels expectedTracingLevel = SourceLevels.All;
string expectedTraceSource = Logger.defaultTraceSource;
string logFilePath = string.Empty;
Logger.Initialize(traceSource: expectedTraceSource, logFilePath: logFilePath, tracingLevel:expectedTracingLevel);
bool isLogFileExpectedToExist = ((uint)expectedTracingLevel >= (uint)SourceLevels.Information);
TestLogger.VerifyInitialization(expectedTracingLevel, expectedTraceSource, Logger.LogFileFullPath, isLogFileExpectedToExist, testNo++);
TestLogger.Cleanup(Logger.LogFileFullPath);
}
//Test 10: Initialization with logfile set to null.
{
SourceLevels expectedTracingLevel = SourceLevels.All;
string expectedTraceSource = Logger.defaultTraceSource;
string logFilePath = null;
Logger.Initialize(traceSource: expectedTraceSource, logFilePath: logFilePath, tracingLevel: expectedTracingLevel);
bool isLogFileExpectedToExist = ((uint)expectedTracingLevel >= (uint)SourceLevels.Information);
TestLogger.VerifyInitialization(expectedTracingLevel, expectedTraceSource, Logger.LogFileFullPath, isLogFileExpectedToExist, testNo++);
TestLogger.Cleanup(Logger.LogFileFullPath);
}
//Test 11: Initialization with LogDirectory in Logger.GenerateLogFilePath set to empty string.
{
SourceLevels expectedTracingLevel = SourceLevels.All;
string expectedTraceSource = Logger.defaultTraceSource;
string logFilePath = Logger.GenerateLogFilePath(Path.Combine(string.Empty, nameof(LoggerTestInitialization)));
Logger.Initialize(traceSource: expectedTraceSource, logFilePath: logFilePath, tracingLevel: expectedTracingLevel);
Assert.True(string.Compare(logFilePath, Logger.LogFileFullPath, ignoreCase: true) == 0, "The logfile should match the path specified");
bool isLogFileExpectedToExist = ((uint)expectedTracingLevel >= (uint)SourceLevels.Information);
TestLogger.VerifyInitialization(expectedTracingLevel, expectedTraceSource, Logger.LogFileFullPath, isLogFileExpectedToExist, testNo++);
TestLogger.Cleanup(Logger.LogFileFullPath);
}
#endregion
}
/// <summary>
/// Test to verify that there is no log file created if TracingLevel is set to off.
/// </summary>
[Test]
public void LoggerTracingLevelOff()
{
TestLogger test = new TestLogger()
{
TraceSource = MethodInfo.GetCurrentMethod().Name,
EventType = TraceEventType.Information,
TracingLevel = SourceLevels.Off,
};
test.Initialize();
test.Write();
Assert.False(File.Exists(Logger.LogFileFullPath), $"Log file must not exist when tracing level is: {test.TracingLevel}");
test.Verify(expectLogMessage: false); // The log message should be absent since the tracing level is set to Off.
test.Cleanup();
}
/// <summary>
/// Test to verify that the tracinglevel setting filters message logged at lower levels.
/// Verifies that a test log entries logged at Information level are not present in log when tracingLevel
/// is set to 'Critical'
/// </summary>
[Test]
public void LoggerInformationalNotLoggedWithCriticalTracingLevel()
{
TestLogger test = new TestLogger()
{
TraceSource = MethodInfo.GetCurrentMethod().Name,
EventType = TraceEventType.Information,
TracingLevel = SourceLevels.Critical,
};
test.Initialize();
test.Write();
test.Verify(expectLogMessage:false); // The log message should be absent since the tracing level is set to collect messages only at 'Critical' logging level
test.Cleanup();
}
/// <summary>
/// Test to verify that WriteWithCallstack() method turns on the callstack logging
/// </summary>
[Test]
public void LoggerWithCallstack()
{
TestLogger test = new TestLogger()
{
TraceSource = MethodInfo.GetCurrentMethod().Name,
EventType = TraceEventType.Warning,
TracingLevel = SourceLevels.Information,
};
test.Initialize();
test.WriteWithCallstack();
test.Verify(); // This should verify the logging of callstack fields as well.
test.Cleanup();
}
/// <summary>
/// Test to verify that callstack logging is turned on, it does not get logged because tracing level filters them out.
/// </summary>
[Test]
public void LoggerWithCallstackFilteredOut()
{
TestLogger test = new TestLogger()
{
TraceSource = MethodInfo.GetCurrentMethod().Name,
EventType = TraceEventType.Information,
TracingLevel = SourceLevels.Error,
};
test.Initialize();
test.WriteWithCallstack();
test.Verify(expectLogMessage:false); // The log message and corresponding callstack details should be absent since the tracing level is set to collect messages only at 'Error' logging level
test.Cleanup();
}
/// <summary>
/// No TraceSource test to verify that WriteWithCallstack() method turns on the callstack logging
/// </summary>
[Test]
public void LoggerNoTraceSourceWithCallstack()
{
TestLogger test = new TestLogger()
{
TraceSource = MethodInfo.GetCurrentMethod().Name,
EventType = TraceEventType.Warning,
TracingLevel = SourceLevels.Information,
DoNotUseTraceSource = true,
};
test.Initialize();
test.WriteWithCallstack();
test.Verify(); // This should verify the logging of callstack fields as well.
test.Cleanup();
}
/// <summary>
/// No TraceSrouce test to verify that callstack logging is turned on, it does not get logged because tracing level filters them out.
/// </summary>
[Test]
public void LoggerNoTraceSourceWithCallstackFilteredOut()
{
TestLogger test = new TestLogger()
{
TraceSource = MethodInfo.GetCurrentMethod().Name,
EventType = TraceEventType.Information,
TracingLevel = SourceLevels.Error,
DoNotUseTraceSource = true,
};
test.Initialize();
test.WriteWithCallstack();
test.Verify(expectLogMessage: false); // The log message and corresponding callstack details should be absent since the tracing level is set to collect messages only at 'Error' logging level
test.Cleanup();
}
/// <summary>
/// Tests to verify that upon changing TracingLevel from Warning To Error,
/// after the change, messages of Error type are present in the log and those logged with warning type are not present.
/// </summary>
[Test]
public void LoggerTracingLevelFromWarningToError()
{
// setup the test object
TestLogger test = new TestLogger()
{
TraceSource = MethodInfo.GetCurrentMethod().Name,
};
TestTracingLevelChangeFromWarningToError(test);
}
/// <summary>
/// Tests to verify that upon changing TracingLevel from Error To Warning,
/// after the change, messages of Warning as well as of Error type are present in the log.
/// </summary>
[Test]
public void LoggerTracingLevelFromErrorToWarning()
{
// setup the test object
TestLogger test = new TestLogger()
{
TraceSource = MethodInfo.GetCurrentMethod().Name,
};
TestTracingLevelChangeFromErrorToWarning(test);
}
/// <summary>
/// When not use TraceSource, test to verify that upon changing TracingLevel from Warning To Error,
/// after the change, messages of Error type are present in the log and those logged with warning type are not present.
/// </summary>
[Test]
public void LoggerNoTraceSourceTracingLevelFromWarningToError()
{
// setup the test object
TestLogger test = new TestLogger()
{
TraceSource = MethodInfo.GetCurrentMethod().Name,
DoNotUseTraceSource = true,
};
TestTracingLevelChangeFromWarningToError(test);
}
/// <summary>
/// Tests out AutoFlush funcitonality. The verification is two fold.
/// 1st is to verify that the setting is persistent.
/// 2nd that after a lot of log entries are written with AutoFlush on, explicitly flushing and closing the Tracing does not increase the file size
/// thereby verifying that there was no leftover log entries being left behind to be flushed.
/// </summary>
[Test]
public void LoggerAutolFlush()
{
// setup the test object
TestLogger test = new TestLogger()
{
TraceSource = MethodInfo.GetCurrentMethod().Name,
AutoFlush = true,
TracingLevel = SourceLevels.All
};
test.Initialize();
// Write 10000 lines of log
Parallel.For(0, 100, (i) => test.Write($"Message Number:{i}, Message:{test.LogMessage}"));
long logContentsSizeBeforeExplicitFlush = (new FileInfo(test.LogFileName)).Length;
// Please note that Logger.Close() first flushes the logs before closing them out.
Logger.Flush();
long logContentsSizeAfterExplicitFlush = (new FileInfo(test.LogFileName)).Length;
Assert.True(logContentsSizeBeforeExplicitFlush == logContentsSizeAfterExplicitFlush, "The length of log file with autoflush before and after explicit flush must be same");
test.Cleanup();
}
/// <summary>
/// When not use TraceSource, test to verify that upon changing TracingLevel from Error To Warning,
/// after the change, messages of Warning as well as of Error type are present in the log.
/// </summary>
[Test]
public void LoggerNoTraceSourceTracingLevelFromErrorToWarning()
{
// setup the test object
TestLogger test = new TestLogger()
{
TraceSource = MethodInfo.GetCurrentMethod().Name,
DoNotUseTraceSource = true,
};
TestTracingLevelChangeFromErrorToWarning(test);
}
private static void TestTracingLevelChangeFromWarningToError(TestLogger test)
{
test.Initialize();
Logger.TracingLevel = SourceLevels.Warning;
string oldMessage = @"Old Message with Tracing Level set to Warning";
test.LogMessage = oldMessage;
// Initially with TracingLevel at Warning, logging of Warning type does not get filtered out.
Assert.AreEqual(SourceLevels.Warning, Logger.TracingLevel);
{
test.EventType = TraceEventType.Warning;
test.Write();
test.PendingVerifications.Add(() =>
{
test.Verify(eventType: TraceEventType.Warning, message: oldMessage, callstackMessage: null, shouldVerifyCallstack: false, expectLogMessage: true);
});
}
// and logging of Error type also succeeeds
{
test.EventType = TraceEventType.Error;
test.Write();
test.PendingVerifications.Add(() =>
{
test.Verify(eventType: TraceEventType.Error, message: oldMessage, callstackMessage: null, shouldVerifyCallstack: false, expectLogMessage: true);
});
}
//Now Update the tracing level to Error. Now logging both of Warning type gets filtered and only Error type should succeed.
Logger.TracingLevel = SourceLevels.Error;
Assert.AreEqual(SourceLevels.Error, Logger.TracingLevel);
string newMessage = @"New Message After Tracing Level set to Error";
test.LogMessage = newMessage;
// Now with TracingLevel at Error, logging of Warning type gets filtered out.
{
test.EventType = TraceEventType.Warning;
test.Write();
test.PendingVerifications.Add(() =>
{
test.Verify(eventType: TraceEventType.Warning, message: newMessage, callstackMessage: null, shouldVerifyCallstack: false, expectLogMessage: false);
});
}
// but logging of Error type succeeds
{
test.EventType = TraceEventType.Error;
test.Write();
test.PendingVerifications.Add(() =>
{
test.Verify(eventType: TraceEventType.Error, message: newMessage, callstackMessage: null, shouldVerifyCallstack: false, expectLogMessage: true);
});
}
test.VerifyPending();
test.Cleanup();
}
private static void TestTracingLevelChangeFromErrorToWarning(TestLogger test)
{
test.Initialize();
Logger.TracingLevel = SourceLevels.Error;
string oldMessage = @"Old Message with Tracing Level set to Error";
test.LogMessage = oldMessage;
// Initially with TracingLevel at Error, logging of Warning type gets filtered out.
Assert.AreEqual(SourceLevels.Error, Logger.TracingLevel);
{
test.EventType = TraceEventType.Warning;
test.Write();
test.PendingVerifications.Add(() =>
{
test.Verify(eventType: TraceEventType.Warning, message: oldMessage, callstackMessage: null, shouldVerifyCallstack: false, expectLogMessage: false);
});
}
// But logging of Error type succeeeds
{
test.EventType = TraceEventType.Error;
test.Write();
test.PendingVerifications.Add(() =>
{
test.Verify(eventType: TraceEventType.Error, message: oldMessage, callstackMessage: null, shouldVerifyCallstack: false, expectLogMessage: true);
});
}
//Now Update the tracing level to Warning. Now logging both of Error type and Warning type should succeed.
Logger.TracingLevel = SourceLevels.Warning;
Assert.AreEqual(SourceLevels.Warning, Logger.TracingLevel);
string newMessage = @"New Message After Tracing Level set to Warning";
test.LogMessage = newMessage;
// Now with TracingLevel at Warning, logging of Warning type does not get filtered out.
{
test.EventType = TraceEventType.Warning;
test.Write();
test.PendingVerifications.Add(() =>
{
test.Verify(eventType: TraceEventType.Warning, message: newMessage, callstackMessage: null, shouldVerifyCallstack: false, expectLogMessage: true);
});
}
// and logging of Error type also succeeds
{
test.EventType = TraceEventType.Error;
test.Write();
test.PendingVerifications.Add(() =>
{
test.Verify(eventType: TraceEventType.Error, message: newMessage, callstackMessage: null, shouldVerifyCallstack: false, expectLogMessage: true);
});
}
test.VerifyPending();
test.Cleanup();
}
}
}
| 49.203252 | 215 | 0.619878 | [
"MIT"
] | KevinRansom/sqltoolsservice | test/Microsoft.SqlTools.ServiceLayer.UnitTests/ServiceHost/LoggerTests.cs | 24,208 | C# |
//
// Copyright © Martin Tamme
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Globalization;
using System.Reflection;
namespace NProxy.Core.Internal.Reflection.Emit
{
/// <summary>
/// Represents the method information base class.
/// </summary>
[Serializable]
internal abstract class MethodInfoBase : MethodInfo
{
/// <summary>
/// The source object.
/// </summary>
private readonly object _source;
/// <summary>
/// The declaring method information.
/// </summary>
private readonly MethodInfo _methodInfo;
/// <summary>
/// A value indicating whether the method is an override.
/// </summary>
private readonly bool _isOverride;
/// <summary>
/// The declaring type.
/// </summary>
private readonly Type _declaringType;
/// <summary>
/// Initializes a new instance of the <see cref="MethodInfoBase"/> class.
/// </summary>
/// <param name="source">The source object.</param>
/// <param name="methodInfo">The declaring method information.</param>
/// <param name="isOverride">A value indicating whether the method is an override.</param>
protected MethodInfoBase(object source, MethodInfo methodInfo, bool isOverride)
{
if (source == null)
throw new ArgumentNullException("source");
if (methodInfo == null)
throw new ArgumentNullException("methodInfo");
_source = source;
_methodInfo = methodInfo;
_isOverride = isOverride;
_declaringType = methodInfo.DeclaringType;
}
/// <summary>
/// Invokes the base method represented by the current instance.
/// </summary>
/// <param name="target">The target object.</param>
/// <param name="parameters">The parameters.</param>
/// <returns>The return value.</returns>
protected virtual object InvokeBase(object target, object[] parameters)
{
throw new TargetException(Resources.MethodNotImplemented);
}
/// <summary>
/// Invokes the virtual method represented by the current instance.
/// </summary>
/// <param name="target">The target object.</param>
/// <param name="parameters">The parameters.</param>
/// <returns>The return value.</returns>
protected abstract object InvokeVirtual(object target, object[] parameters);
#region MethodInfo Members
/// <inheritdoc/>
public override sealed ParameterInfo ReturnParameter
{
get { return _methodInfo.ReturnParameter; }
}
/// <inheritdoc/>
public override sealed Type ReturnType
{
get { return _methodInfo.ReturnType; }
}
/// <inheritdoc/>
public override sealed ICustomAttributeProvider ReturnTypeCustomAttributes
{
get { return _methodInfo.ReturnTypeCustomAttributes; }
}
/// <inheritdoc/>
public override sealed MethodInfo GetBaseDefinition()
{
return _methodInfo.GetBaseDefinition();
}
/// <inheritdoc/>
public override sealed MethodInfo GetGenericMethodDefinition()
{
return _methodInfo.GetGenericMethodDefinition();
}
/// <inheritdoc/>
public override sealed MethodInfo MakeGenericMethod(params Type[] typeArguments)
{
return _methodInfo.MakeGenericMethod(typeArguments);
}
#endregion
#region MethodBase Members
/// <inheritdoc/>
public override sealed MethodAttributes Attributes
{
get { return _methodInfo.Attributes; }
}
/// <inheritdoc/>
public override sealed CallingConventions CallingConvention
{
get { return _methodInfo.CallingConvention; }
}
/// <inheritdoc/>
public override sealed bool ContainsGenericParameters
{
get { return _methodInfo.ContainsGenericParameters; }
}
/// <inheritdoc/>
public override sealed bool IsGenericMethod
{
get { return _methodInfo.IsGenericMethod; }
}
/// <inheritdoc/>
public override sealed bool IsGenericMethodDefinition
{
get { return _methodInfo.IsGenericMethodDefinition; }
}
/// <inheritdoc/>
public override sealed RuntimeMethodHandle MethodHandle
{
get { return _methodInfo.MethodHandle; }
}
/// <inheritdoc/>
public override sealed Type[] GetGenericArguments()
{
return _methodInfo.GetGenericArguments();
}
/// <inheritdoc/>
public override sealed MethodBody GetMethodBody()
{
return _methodInfo.GetMethodBody();
}
/// <inheritdoc/>
public override sealed MethodImplAttributes GetMethodImplementationFlags()
{
return _methodInfo.GetMethodImplementationFlags();
}
/// <inheritdoc/>
public override sealed ParameterInfo[] GetParameters()
{
return _methodInfo.GetParameters();
}
/// <inheritdoc/>
public override sealed object Invoke(object target, BindingFlags bindingFlags, Binder binder, object[] parameters, CultureInfo cultureInfo)
{
// Invoke base method when target equals source object.
if (ReferenceEquals(target, _source))
{
if (_isOverride)
return InvokeBase(target, parameters);
throw new TargetException(Resources.MethodNotImplemented);
}
if (target == null)
throw new TargetException(Resources.MethodRequiresATargetObject);
// Check target type.
var targetType = target.GetType();
if (!_declaringType.IsAssignableFrom(targetType) && !targetType.IsCOMObject)
throw new TargetException(Resources.MethodNotDeclaredOrInherited);
// Invoke method on target object.
return InvokeVirtual(target, parameters);
}
#endregion
#region ICustomAttributeProvider Members
/// <inheritdoc/>
public override sealed object[] GetCustomAttributes(Type attributeType, bool inherit)
{
return _methodInfo.GetCustomAttributes(attributeType, inherit);
}
/// <inheritdoc/>
public override sealed object[] GetCustomAttributes(bool inherit)
{
return _methodInfo.GetCustomAttributes(inherit);
}
/// <inheritdoc/>
public override sealed bool IsDefined(Type attributeType, bool inherit)
{
return _methodInfo.IsDefined(attributeType, inherit);
}
#endregion
#region MemberInfo Members
/// <inheritdoc/>
public override sealed Type DeclaringType
{
get { return _declaringType; }
}
/// <inheritdoc/>
public override sealed MemberTypes MemberType
{
get { return _methodInfo.MemberType; }
}
/// <inheritdoc/>
public override sealed int MetadataToken
{
get { return _methodInfo.MetadataToken; }
}
/// <inheritdoc/>
public override sealed Module Module
{
get { return _methodInfo.Module; }
}
/// <inheritdoc/>
public override sealed string Name
{
get { return _methodInfo.Name; }
}
/// <inheritdoc/>
public override sealed Type ReflectedType
{
get { return _methodInfo.ReflectedType; }
}
#endregion
#region Object Members
/// <inheritdoc/>
public override sealed bool Equals(object obj)
{
return _methodInfo.Equals(obj);
}
/// <inheritdoc/>
public override sealed int GetHashCode()
{
return _methodInfo.GetHashCode();
}
/// <inheritdoc/>
public override sealed string ToString()
{
return _methodInfo.ToString();
}
#endregion
}
} | 29.665563 | 147 | 0.590244 | [
"Apache-2.0"
] | mtamme/NProxy | Source/Main/NProxy.Core/Internal/Reflection/Emit/MethodInfoBase.cs | 8,960 | 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.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void MinDouble()
{
var test = new SimpleBinaryOpTest__MinDouble();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__MinDouble
{
private const int VectorSize = 16;
private const int Op1ElementCount = VectorSize / sizeof(Double);
private const int Op2ElementCount = VectorSize / sizeof(Double);
private const int RetElementCount = VectorSize / sizeof(Double);
private static Double[] _data1 = new Double[Op1ElementCount];
private static Double[] _data2 = new Double[Op2ElementCount];
private static Vector128<Double> _clsVar1;
private static Vector128<Double> _clsVar2;
private Vector128<Double> _fld1;
private Vector128<Double> _fld2;
private SimpleBinaryOpTest__DataTable<Double, Double, Double> _dataTable;
static SimpleBinaryOpTest__MinDouble()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (double)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), VectorSize);
}
public SimpleBinaryOpTest__MinDouble()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (double)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (double)(random.NextDouble()); }
_dataTable = new SimpleBinaryOpTest__DataTable<Double, Double, Double>(_data1, _data2, new Double[RetElementCount], VectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse2.Min(
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Sse2.Min(
Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse2.Min(
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.Min), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.Min), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.Min), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Sse2.Min(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr);
var result = Sse2.Min(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr));
var result = Sse2.Min(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr));
var result = Sse2.Min(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__MinDouble();
var result = Sse2.Min(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Sse2.Min(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<Double> left, Vector128<Double> right, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "")
{
if (BitConverter.DoubleToInt64Bits(Math.Min(left[0], right[0])) != BitConverter.DoubleToInt64Bits(result[0]))
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.DoubleToInt64Bits(Math.Min(left[i], right[i])) != BitConverter.DoubleToInt64Bits(result[i]))
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.Min)}<Double>(Vector128<Double>, Vector128<Double>): {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| 41.966767 | 148 | 0.574185 | [
"MIT"
] | ruben-ayrapetyan/coreclr | tests/src/JIT/HardwareIntrinsics/X86/Sse2/Min.Double.cs | 13,891 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using System.Collections;
using Microsoft.EnterpriseManagement.Common;
using Microsoft.EnterpriseManagement.UI.Core.Connection;
using Microsoft.EnterpriseManagement.ConsoleFramework;
using Microsoft.EnterpriseManagement.Configuration;
using Microsoft.EnterpriseManagement.UI.SdkDataAccess.DataAdapters;
using Microsoft.EnterpriseManagement.GenericForm;
using Microsoft.EnterpriseManagement;
using Microsoft.EnterpriseManagement.ServiceManager.Application.Common;
////Requires Microsoft.EnterpriseManagement.UI.SMControls
using Microsoft.EnterpriseManagement.UI.WpfControls; //Contains InstancePickerDialog, UserPicker, and ListPicker
////Requires Microsoft.EnterpriseManagement.UI.WpfViews
using Microsoft.EnterpriseManagement.UI.WpfViews; //Contains FormEvents
//// Requires Microsoft.EnterpriseManagement.UI.Foundation
using Microsoft.EnterpriseManagement.UI.DataModel; //Contains IDataItem
////Requires Microsoft.EnterpriseManagement.UI.FormsInfra
using Microsoft.EnterpriseManagement.UI.FormsInfra; //Contains PreviewFormCommandEventArgs
namespace ITAssetMgmtForms
{
/// <summary>
/// Interaction logic for AzureResourceGroupForm.xaml
/// </summary>
public partial class AzureResourceGroupForm : UserControl
{
private RelatedItemsPane _relatedItemsPane;
public AzureResourceGroupForm()
{
InitializeComponent();
_relatedItemsPane = new RelatedItemsPane(new ConfigItemRelatedItemsConfiguration());
tabItemRelItems.Content = _relatedItemsPane;
}
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
this.AddHandler(FormEvents.PreviewSubmitEvent, new EventHandler<PreviewFormCommandEventArgs>(this.OnPreviewSubmit));
}
private void OnPreviewSubmit(object sender, PreviewFormCommandEventArgs e)
{
IDataItem ResourceName = this.DataContext as IDataItem;
String strResourceName;
strResourceName = ResourceName["ResourceName"].ToString();
ResourceName["ResourceName"] = strResourceName;
}
private void expMain_Loaded(object sender, RoutedEventArgs e)
{
HeaderedContentControl headeredContentControl = new HeaderedContentControl();
headeredContentControl.OverridesDefaultStyle = true;
headeredContentControl.Foreground = Brushes.Black;
headeredContentControl.Header = "Main";
this.expMain.Header = headeredContentControl;
}
private void expDetails_Loaded(object sender, RoutedEventArgs e)
{
HeaderedContentControl headeredContentControl = new HeaderedContentControl();
headeredContentControl.OverridesDefaultStyle = true;
headeredContentControl.Foreground = Brushes.Black;
headeredContentControl.Header = "References";
this.expDetails.Header = headeredContentControl;
}
//
private void btnAdd_Click_VMs(object sender, RoutedEventArgs e)
{
AddItemToListView(this.VMs, ITAssetMgmtForms.Resources.guidAzureVM);
}
private void btnRemove_Click_VMs(object sender, RoutedEventArgs e)
{
RemoveItemFromWorkItemListView(this.VMs);
}
private void btnOpen_Click_VMs(object sender, RoutedEventArgs e)
{
IDataItem emoProjectionObject = (IDataItem)VMs.SelectedItem;
Microsoft.EnterpriseManagement.GenericForm.FormUtilities.Instance.PopoutForm(emoProjectionObject);
}
private void MouseDoubleClick_VMs(object sender, MouseButtonEventArgs e)
{
IDataItem emoProjectionObject = (IDataItem)VMs.SelectedItem;
Microsoft.EnterpriseManagement.GenericForm.FormUtilities.Instance.PopoutForm(emoProjectionObject);
}
//
private void btnAdd_Click_AzureNetwork(object sender, RoutedEventArgs e)
{
AddItemToListView(this.AzureNetwork, ITAssetMgmtForms.Resources.guidAzureNet);
}
private void btnRemove_Click_AzureNetwork(object sender, RoutedEventArgs e)
{
RemoveItemFromWorkItemListView(this.AzureNetwork);
}
private void btnOpen_Click_AzureNetwork(object sender, RoutedEventArgs e)
{
IDataItem emoProjectionObject = (IDataItem)AzureNetwork.SelectedItem;
Microsoft.EnterpriseManagement.GenericForm.FormUtilities.Instance.PopoutForm(emoProjectionObject);
}
private void MouseDoubleClick_AzureNetwork(object sender, MouseButtonEventArgs e)
{
IDataItem emoProjectionObject = (IDataItem)AzureNetwork.SelectedItem;
Microsoft.EnterpriseManagement.GenericForm.FormUtilities.Instance.PopoutForm(emoProjectionObject);
}
//
private void btnAdd_Click_AzureWebApplication(object sender, RoutedEventArgs e)
{
AddItemToListView(this.AzureWebApplication, ITAssetMgmtForms.Resources.guidAzureWebAppClass);
}
private void btnRemove_Click_AzureWebApplication(object sender, RoutedEventArgs e)
{
RemoveItemFromWorkItemListView(this.AzureWebApplication);
}
private void btnOpen_Click_AzureWebApplication(object sender, RoutedEventArgs e)
{
IDataItem emoProjectionObject = (IDataItem)AzureWebApplication.SelectedItem;
Microsoft.EnterpriseManagement.GenericForm.FormUtilities.Instance.PopoutForm(emoProjectionObject);
}
private void MouseDoubleClick_AzureWebApplication(object sender, MouseButtonEventArgs e)
{
IDataItem emoProjectionObject = (IDataItem)AzureWebApplication.SelectedItem;
Microsoft.EnterpriseManagement.GenericForm.FormUtilities.Instance.PopoutForm(emoProjectionObject);
}
//
private void btnAdd_Click_SQLServer(object sender, RoutedEventArgs e)
{
AddItemToListView(this.SQLServer, ITAssetMgmtForms.Resources.guidAzureSQlServerClass);
}
private void btnRemove_Click_SQLServer(object sender, RoutedEventArgs e)
{
RemoveItemFromWorkItemListView(this.SQLServer);
}
private void btnOpen_Click_SQLServer(object sender, RoutedEventArgs e)
{
IDataItem emoProjectionObject = (IDataItem)SQLServer.SelectedItem;
Microsoft.EnterpriseManagement.GenericForm.FormUtilities.Instance.PopoutForm(emoProjectionObject);
}
private void MouseDoubleClick_SQLServer(object sender, MouseButtonEventArgs e)
{
IDataItem emoProjectionObject = (IDataItem)SQLServer.SelectedItem;
Microsoft.EnterpriseManagement.GenericForm.FormUtilities.Instance.PopoutForm(emoProjectionObject);
}
//
internal static void AddItemToListView(ListView listView, Guid classId)
{
if (listView != null && listView.Items != null)
{
InstancePickerDialog ciPicker = new InstancePickerDialog();
ciPicker.ClassId = classId;
ciPicker.SelectionMode = SelectionMode.Multiple;
if (listView.Items.Count > 0)
{
ciPicker.SetPickedInstances((Collection<IDataItem>)listView.ItemsSource);
}
bool? result = ciPicker.ShowDialog();
if (result != null && result == true)
{
Collection<IDataItem> items = listView.ItemsSource as Collection<IDataItem>;
foreach (IDataItem item in ciPicker.RemovedInstances)
items.Remove(item);
foreach (IDataItem item in ciPicker.PickedInstances)
if (!items.Contains(item))
items.Add(item);
}
}
}
internal static void RemoveItemFromWorkItemListView(ListView listView)
{
if (listView.ItemsSource == null ||
listView.SelectedItems == null ||
listView.SelectedItems.Count == 0)
{
return;
}
Collection<IDataItem> items = listView.ItemsSource as Collection<IDataItem>;
if (items != null)
{
foreach (object obj in new ArrayList(listView.SelectedItems))
{
/* NOTE: The use of the IDataItem interface here is not supported/documented.
* This interface may change in the future and no migration path is guaranteed
by Microsoft.
*/
items.Remove(obj as IDataItem);
}
}
}
private void InstancePicker_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
SingleInstancePicker singleInstancePicker = (SingleInstancePicker)sender;
FormUtilities.Instance.PopoutForm(singleInstancePicker.Instance);
}
private void AzureNetwork_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
}
private void VMs_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
}
private void SQLServer_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
}
private void AzureWebApplication_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
}
}
}
| 38.616279 | 128 | 0.676503 | [
"MIT"
] | evkapsal/SCSM-2016-IT-Asset-Management | ITAssetMgmtForms/ITAssetMgmtForms/AzureResourceGroupForm.xaml.cs | 9,965 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.