content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
namespace Kentico.Kontent.Management.Models.Collections;
/// <summary>
/// Represents content collections
/// </summary>
public class CollectionsModel
{
/// <summary>
/// Gets or sets the list of content collections
/// </summary>
[JsonProperty("collections")]
public IEnumerable<CollectionModel> Collections { get; set; }
/// <summary>
/// Gets or sets the ISO-8601 formatted date and time of the last change to content collections.
/// This property can be null if the collections were not changed yet.
/// </summary>
[JsonProperty("last_modified")]
public DateTime? LastModified { get; set; }
}
| 28.68 | 100 | 0.698745 | [
"MIT"
] | Kentico/content-management-sdk-net | Kentico.Kontent.Management/Models/Collections/CollectionsModel.cs | 719 | C# |
using Amplifier;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Siya
{
public partial class nd
{
internal static dynamic exec = null;
public static void use_device(int id = 0)
{
compiler.UseDevice(id);
compiler.CompileKernel(get_source());
exec = compiler.Exec;
}
private static string get_source()
{
StringBuilder sb = new StringBuilder();
DirectoryInfo dir = new DirectoryInfo("./kernels/");
var files = dir.GetFiles("*.cu");
foreach (var file in files)
{
if(file.Name.StartsWith("template_"))
{
string template = file.OpenText().ReadToEnd();
sb.AppendLine(template.Replace("<DTYPE_NAME>", "float"));
sb.AppendLine(template.Replace("<DTYPE_NAME>", "double"));
//template = template.Replace("fabs(", "abs(");
//sb.AppendLine(template.Replace("<DTYPE_NAME>", "char"));
//sb.AppendLine(template.Replace("<DTYPE_NAME>", "uchar"));
//sb.AppendLine(template.Replace("<DTYPE_NAME>", "short"));
//sb.AppendLine(template.Replace("<DTYPE_NAME>", "int"));
//sb.AppendLine(template.Replace("<DTYPE_NAME>", "long"));
//sb.AppendLine(template.Replace("<DTYPE_NAME>", "ushort"));
//sb.AppendLine(template.Replace("<DTYPE_NAME>", "uint"));
//sb.AppendLine(template.Replace("<DTYPE_NAME>", "ulong"));
//sb.AppendLine(template.Replace("<DTYPE_NAME>", "bool"));
}
sb.AppendLine();
}
return sb.ToString();
}
internal static NDArray unary_exec(NDArray x, string function)
{
var (dtype, dtype_str) = check_and_get_dtype(new NDArray[] { x });
NDArray r = new NDArray(x.shape, dtype);
compiler.Execute($"{dtype_str}_{function}", x, r);
return r;
}
internal static NDArray binary_exec(NDArray x1, NDArray x2, string function)
{
var (dtype, dtype_str) = check_and_get_dtype(new NDArray[] { x1, x2 });
NDArray r = new NDArray(x1.shape, dtype);
compiler.Execute($"{dtype_str}_{function}", x1, x2, r);
return r;
}
internal static NDArray full_exec(double fill_value, NDArray x)
{
var (dtype, dtype_str) = check_and_get_dtype(new NDArray[] { x });
compiler.Execute($"{dtype_str}_full", fill_value, x);
return x;
}
internal static (DType, string) check_and_get_dtype(NDArray[] arrays)
{
if (exec == null)
use_device();
int size = arrays[0].dtype.Size();
DType finalDtype = arrays[0].dtype;
foreach (var item in arrays)
{
if (item.dtype.Size() > size)
{
size = item.dtype.Size();
finalDtype = item.dtype;
}
}
return (finalDtype, get_dtype_str(finalDtype));
}
private static string get_dtype_str(DType dtype)
{
switch (dtype)
{
case DType.Float32:
return "float";
case DType.Float64:
return "double";
case DType.Int8:
return "float";
case DType.Int16:
return "float";
case DType.Int32:
return "float";
case DType.Int64:
return "double";
case DType.UInt8:
return "float";
case DType.UInt16:
return "float";
case DType.UInt32:
return "float";
case DType.UInt64:
return "double";
case DType.Bool:
return "float";
default:
return "float";
}
}
}
}
| 34.848 | 84 | 0.48393 | [
"MIT"
] | csrakowski/Amplifier.NET | src/Siya/CompilerUtility.cs | 4,358 | C# |
using System;
using System.Net.Http.Headers;
using System.Web.Http.Filters;
namespace SharpDevelopWebApi.Helpers.JWT
{
public static class HttpAuthenticationChallengeContextExtensions
{
public static void ChallengeWith(this HttpAuthenticationChallengeContext context, string scheme)
{
ChallengeWith(context, new AuthenticationHeaderValue(scheme));
}
public static void ChallengeWith(this HttpAuthenticationChallengeContext context, string scheme, string parameter)
{
ChallengeWith(context, new AuthenticationHeaderValue(scheme, parameter));
}
public static void ChallengeWith(this HttpAuthenticationChallengeContext context, AuthenticationHeaderValue challenge)
{
if (context == null)
{
//throw new ArgumentNullException(nameof(context));
}
context.Result = new AddChallengeOnUnauthorizedResult(challenge, context.Result);
}
}
}
| 33.533333 | 126 | 0.691849 | [
"MIT"
] | Mjjunco/ExamStudents | Helpers/JWT/HttpAuthenticationChallengeContextExtensions.cs | 1,008 | 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.ApiManagement.V20200601Preview.Inputs
{
/// <summary>
/// Details of the Credentials used to connect to Backend.
/// </summary>
public sealed class BackendCredentialsContractArgs : Pulumi.ResourceArgs
{
/// <summary>
/// Authorization header authentication
/// </summary>
[Input("authorization")]
public Input<Inputs.BackendAuthorizationHeaderCredentialsArgs>? Authorization { get; set; }
[Input("certificate")]
private InputList<string>? _certificate;
/// <summary>
/// List of Client Certificate Thumbprint.
/// </summary>
public InputList<string> Certificate
{
get => _certificate ?? (_certificate = new InputList<string>());
set => _certificate = value;
}
[Input("header")]
private InputMap<ImmutableArray<string>>? _header;
/// <summary>
/// Header Parameter description.
/// </summary>
public InputMap<ImmutableArray<string>> Header
{
get => _header ?? (_header = new InputMap<ImmutableArray<string>>());
set => _header = value;
}
[Input("query")]
private InputMap<ImmutableArray<string>>? _query;
/// <summary>
/// Query Parameter description.
/// </summary>
public InputMap<ImmutableArray<string>> Query
{
get => _query ?? (_query = new InputMap<ImmutableArray<string>>());
set => _query = value;
}
public BackendCredentialsContractArgs()
{
}
}
}
| 29.907692 | 99 | 0.600823 | [
"Apache-2.0"
] | test-wiz-sec/pulumi-azure-nextgen | sdk/dotnet/ApiManagement/V20200601Preview/Inputs/BackendCredentialsContractArgs.cs | 1,944 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.IO;
using Microsoft.AspNetCore.Hosting;
namespace FormatterWebSite;
public class Program
{
public static void Main(string[] args)
{
var host = CreateWebHostBuilder(args)
.Build();
host.Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
new WebHostBuilder()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseStartup<Startup>()
.UseKestrel()
.UseIISIntegration();
}
| 25 | 72 | 0.653846 | [
"MIT"
] | AndrewTriesToCode/aspnetcore | src/Mvc/test/WebSites/FormatterWebSite/Program.cs | 652 | C# |
namespace BinaryDataSerialization.Test.WhenNot
{
public class WhenNotClass
{
[FieldOrder(0)]
public bool ExcludeValue { get; set; }
[FieldOrder(1)]
[SerializeWhenNot(nameof(ExcludeValue), true)]
public int Value { get; set; }
}
}
| 21.846154 | 54 | 0.612676 | [
"MIT"
] | jackwakefield/BinaryDataSerializer | BinaryDataSerializer.Test/WhenNot/WhenNotClass.cs | 286 | C# |
//This file contains all the signals that are dispatched between Contexts
using System;
using strange.extensions.signal.impl;
namespace TeamBrookvale
{
public class StartSignal : Signal {}
public class PlayerGotoSignal : Signal<TouchScreenPosition> {}
public class PlayerActionSignal : Signal<TouchScreenPosition,bool> {} // true when starting action, false when finishing
public class InventoryIconPressSignal : Signal<bool> {}
public class PauseResumeLevelPassedFailedSignal : Signal<TeamBrookvale.UI.InGameMenuModel.MenuState> {}
public class CurrentInventoryIconSignal : Signal<TeamBrookvale.Game.InvItem.IDType> {} // sent once the new button became active
// Inventory event signals
public class InventoryEventFireSignal: Signal<TeamBrookvale.Game.InventoryModel.Events, TouchScreenPosition> {}
public class LoadNextLevelSignal : Signal {}
public class RetryLevelSignal : Signal {}
// Status bar message
public class StatusBarMessageSignal : Signal<string> {}
public class StatusBarMessageRemoveSignal : Signal<string> {}
/*
//Input
public class GameInputSignal : Signal<int>{};
//Game
public class GameStartSignal : Signal{}
public class GameEndSignal : Signal{}
public class LevelStartSignal : Signal{}
public class LevelEndSignal : Signal{}
public class UpdateLivesSignal : Signal<int>{}
public class UpdateScoreSignal : Signal<int>{}
public class UpdateLevelSignal : Signal<int>{}
*/
}
| 34.642857 | 129 | 0.772509 | [
"Apache-2.0"
] | TeamBrookvale/Saboteur-Diver | Assets/Scripts/MVCS/Common/Config/CrossContextSignals.cs | 1,455 | C# |
/*******************************************************************************
* Copyright 2012-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file.
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
* *****************************************************************************
*
* AWS Tools for Windows (TM) PowerShell (TM)
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using System.Text;
using Amazon.PowerShell.Common;
using Amazon.Runtime;
using Amazon.ApplicationAutoScaling;
using Amazon.ApplicationAutoScaling.Model;
namespace Amazon.PowerShell.Cmdlets.AAS
{
/// <summary>
/// Creates or updates a policy for an Application Auto Scaling scalable target.
///
///
/// <para>
/// Each scalable target is identified by a service namespace, resource ID, and scalable
/// dimension. A scaling policy applies to the scalable target identified by those three
/// attributes. You cannot create a scaling policy until you have registered the resource
/// as a scalable target using <a>RegisterScalableTarget</a>.
/// </para><para>
/// To update a policy, specify its policy name and the parameters that you want to change.
/// Any parameters that you don't specify are not changed by this update request.
/// </para><para>
/// You can view the scaling policies for a service namespace using <a>DescribeScalingPolicies</a>.
/// If you are no longer using a scaling policy, you can delete it using <a>DeleteScalingPolicy</a>.
/// </para><para>
/// Multiple scaling policies can be in force at the same time for the same scalable target.
/// You can have one or more target tracking scaling policies, one or more step scaling
/// policies, or both. However, there is a chance that multiple policies could conflict,
/// instructing the scalable target to scale out or in at the same time. Application Auto
/// Scaling gives precedence to the policy that provides the largest capacity for both
/// scale out and scale in. For example, if one policy increases capacity by 3, another
/// policy increases capacity by 200 percent, and the current capacity is 10, Application
/// Auto Scaling uses the policy with the highest calculated capacity (200% of 10 = 20)
/// and scales out to 30.
/// </para><para>
/// Learn more about how to work with scaling policies in the <a href="https://docs.aws.amazon.com/autoscaling/application/userguide/what-is-application-auto-scaling.html">Application
/// Auto Scaling User Guide</a>.
/// </para>
/// </summary>
[Cmdlet("Set", "AASScalingPolicy", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.Medium)]
[OutputType("Amazon.ApplicationAutoScaling.Model.PutScalingPolicyResponse")]
[AWSCmdlet("Calls the Application Auto Scaling PutScalingPolicy API operation.", Operation = new[] {"PutScalingPolicy"}, SelectReturnType = typeof(Amazon.ApplicationAutoScaling.Model.PutScalingPolicyResponse), LegacyAlias="Write-AASScalingPolicy")]
[AWSCmdletOutput("Amazon.ApplicationAutoScaling.Model.PutScalingPolicyResponse",
"This cmdlet returns an Amazon.ApplicationAutoScaling.Model.PutScalingPolicyResponse object containing multiple properties. The object can also be referenced from properties attached to the cmdlet entry in the $AWSHistory stack."
)]
public partial class SetAASScalingPolicyCmdlet : AmazonApplicationAutoScalingClientCmdlet, IExecutor
{
#region Parameter StepScalingPolicyConfiguration_AdjustmentType
/// <summary>
/// <para>
/// <para>Specifies whether the <code>ScalingAdjustment</code> value in a <a>StepAdjustment</a>
/// is an absolute number or a percentage of the current capacity. </para>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
[AWSConstantClassSource("Amazon.ApplicationAutoScaling.AdjustmentType")]
public Amazon.ApplicationAutoScaling.AdjustmentType StepScalingPolicyConfiguration_AdjustmentType { get; set; }
#endregion
#region Parameter StepScalingPolicyConfiguration_Cooldown
/// <summary>
/// <para>
/// <para>The amount of time, in seconds, after a scaling activity completes where previous
/// trigger-related scaling activities can influence future scaling events.</para><para>For scale-out policies, while the cooldown period is in effect, the capacity that
/// has been added by the previous scale-out event that initiated the cooldown is calculated
/// as part of the desired capacity for the next scale out. The intention is to continuously
/// (but not excessively) scale out. For example, an alarm triggers a step scaling policy
/// to scale out an Amazon ECS service by 2 tasks, the scaling activity completes successfully,
/// and a cooldown period of 5 minutes starts. During the cooldown period, if the alarm
/// triggers the same policy again but at a more aggressive step adjustment to scale out
/// the service by 3 tasks, the 2 tasks that were added in the previous scale-out event
/// are considered part of that capacity and only 1 additional task is added to the desired
/// count.</para><para>For scale-in policies, the cooldown period is used to block subsequent scale-in requests
/// until it has expired. The intention is to scale in conservatively to protect your
/// application's availability. However, if another alarm triggers a scale-out policy
/// during the cooldown period after a scale-in, Application Auto Scaling scales out your
/// scalable target immediately.</para>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public System.Int32? StepScalingPolicyConfiguration_Cooldown { get; set; }
#endregion
#region Parameter CustomizedMetricSpecification_Dimension
/// <summary>
/// <para>
/// <para>The dimensions of the metric. </para><para>Conditional: If you published your metric with dimensions, you must specify the same
/// dimensions in your scaling policy.</para>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
[Alias("TargetTrackingScalingPolicyConfiguration_CustomizedMetricSpecification_Dimensions")]
public Amazon.ApplicationAutoScaling.Model.MetricDimension[] CustomizedMetricSpecification_Dimension { get; set; }
#endregion
#region Parameter TargetTrackingScalingPolicyConfiguration_DisableScaleIn
/// <summary>
/// <para>
/// <para>Indicates whether scale in by the target tracking scaling policy is disabled. If the
/// value is <code>true</code>, scale in is disabled and the target tracking scaling policy
/// won't remove capacity from the scalable resource. Otherwise, scale in is enabled and
/// the target tracking scaling policy can remove capacity from the scalable resource.
/// The default value is <code>false</code>.</para>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public System.Boolean? TargetTrackingScalingPolicyConfiguration_DisableScaleIn { get; set; }
#endregion
#region Parameter StepScalingPolicyConfiguration_MetricAggregationType
/// <summary>
/// <para>
/// <para>The aggregation type for the CloudWatch metrics. Valid values are <code>Minimum</code>,
/// <code>Maximum</code>, and <code>Average</code>. If the aggregation type is null, the
/// value is treated as <code>Average</code>.</para>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
[AWSConstantClassSource("Amazon.ApplicationAutoScaling.MetricAggregationType")]
public Amazon.ApplicationAutoScaling.MetricAggregationType StepScalingPolicyConfiguration_MetricAggregationType { get; set; }
#endregion
#region Parameter CustomizedMetricSpecification_MetricName
/// <summary>
/// <para>
/// <para>The name of the metric. </para>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
[Alias("TargetTrackingScalingPolicyConfiguration_CustomizedMetricSpecification_MetricName")]
public System.String CustomizedMetricSpecification_MetricName { get; set; }
#endregion
#region Parameter StepScalingPolicyConfiguration_MinAdjustmentMagnitude
/// <summary>
/// <para>
/// <para>The minimum number to adjust your scalable dimension as a result of a scaling activity.
/// If the adjustment type is <code>PercentChangeInCapacity</code>, the scaling policy
/// changes the scalable dimension of the scalable target by this amount.</para><para>For example, suppose that you create a step scaling policy to scale out an Amazon
/// ECS service by 25 percent and you specify a <code>MinAdjustmentMagnitude</code> of
/// 2. If the service has 4 tasks and the scaling policy is performed, 25 percent of 4
/// is 1. However, because you specified a <code>MinAdjustmentMagnitude</code> of 2, Application
/// Auto Scaling scales out the service by 2 tasks.</para>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public System.Int32? StepScalingPolicyConfiguration_MinAdjustmentMagnitude { get; set; }
#endregion
#region Parameter CustomizedMetricSpecification_Namespace
/// <summary>
/// <para>
/// <para>The namespace of the metric.</para>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
[Alias("TargetTrackingScalingPolicyConfiguration_CustomizedMetricSpecification_Namespace")]
public System.String CustomizedMetricSpecification_Namespace { get; set; }
#endregion
#region Parameter PolicyName
/// <summary>
/// <para>
/// <para>The name of the scaling policy.</para>
/// </para>
/// </summary>
#if !MODULAR
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
#else
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true, Mandatory = true)]
[System.Management.Automation.AllowEmptyString]
[System.Management.Automation.AllowNull]
#endif
[Amazon.PowerShell.Common.AWSRequiredParameter]
public System.String PolicyName { get; set; }
#endregion
#region Parameter PolicyType
/// <summary>
/// <para>
/// <para>The policy type. This parameter is required if you are creating a scaling policy.</para><para>The following policy types are supported: </para><para><code>TargetTrackingScaling</code>—Not supported for Amazon EMR</para><para><code>StepScaling</code>—Not supported for DynamoDB, Amazon Comprehend, or AWS Lambda</para><para>For more information, see <a href="https://docs.aws.amazon.com/autoscaling/application/userguide/application-auto-scaling-target-tracking.html">Target
/// Tracking Scaling Policies</a> and <a href="https://docs.aws.amazon.com/autoscaling/application/userguide/application-auto-scaling-step-scaling-policies.html">Step
/// Scaling Policies</a> in the <i>Application Auto Scaling User Guide</i>.</para>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
[AWSConstantClassSource("Amazon.ApplicationAutoScaling.PolicyType")]
public Amazon.ApplicationAutoScaling.PolicyType PolicyType { get; set; }
#endregion
#region Parameter PredefinedMetricSpecification_PredefinedMetricType
/// <summary>
/// <para>
/// <para>The metric type. The <code>ALBRequestCountPerTarget</code> metric type applies only
/// to Spot Fleet requests and ECS services.</para>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
[Alias("TargetTrackingScalingPolicyConfiguration_PredefinedMetricSpecification_PredefinedMetricType")]
[AWSConstantClassSource("Amazon.ApplicationAutoScaling.MetricType")]
public Amazon.ApplicationAutoScaling.MetricType PredefinedMetricSpecification_PredefinedMetricType { get; set; }
#endregion
#region Parameter ResourceId
/// <summary>
/// <para>
/// <para>The identifier of the resource associated with the scaling policy. This string consists
/// of the resource type and unique identifier.</para><ul><li><para>ECS service - The resource type is <code>service</code> and the unique identifier
/// is the cluster name and service name. Example: <code>service/default/sample-webapp</code>.</para></li><li><para>Spot Fleet request - The resource type is <code>spot-fleet-request</code> and the
/// unique identifier is the Spot Fleet request ID. Example: <code>spot-fleet-request/sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE</code>.</para></li><li><para>EMR cluster - The resource type is <code>instancegroup</code> and the unique identifier
/// is the cluster ID and instance group ID. Example: <code>instancegroup/j-2EEZNYKUA1NTV/ig-1791Y4E1L8YI0</code>.</para></li><li><para>AppStream 2.0 fleet - The resource type is <code>fleet</code> and the unique identifier
/// is the fleet name. Example: <code>fleet/sample-fleet</code>.</para></li><li><para>DynamoDB table - The resource type is <code>table</code> and the unique identifier
/// is the table name. Example: <code>table/my-table</code>.</para></li><li><para>DynamoDB global secondary index - The resource type is <code>index</code> and the
/// unique identifier is the index name. Example: <code>table/my-table/index/my-table-index</code>.</para></li><li><para>Aurora DB cluster - The resource type is <code>cluster</code> and the unique identifier
/// is the cluster name. Example: <code>cluster:my-db-cluster</code>.</para></li><li><para>Amazon SageMaker endpoint variant - The resource type is <code>variant</code> and
/// the unique identifier is the resource ID. Example: <code>endpoint/my-end-point/variant/KMeansClustering</code>.</para></li><li><para>Custom resources are not supported with a resource type. This parameter must specify
/// the <code>OutputValue</code> from the CloudFormation template stack used to access
/// the resources. The unique identifier is defined by the service provider. More information
/// is available in our <a href="https://github.com/aws/aws-auto-scaling-custom-resource">GitHub
/// repository</a>.</para></li><li><para>Amazon Comprehend document classification endpoint - The resource type and unique
/// identifier are specified using the endpoint ARN. Example: <code>arn:aws:comprehend:us-west-2:123456789012:document-classifier-endpoint/EXAMPLE</code>.</para></li><li><para>Lambda provisioned concurrency - The resource type is <code>function</code> and the
/// unique identifier is the function name with a function version or alias name suffix
/// that is not <code>$LATEST</code>. Example: <code>function:my-function:prod</code>
/// or <code>function:my-function:1</code>.</para></li></ul>
/// </para>
/// </summary>
#if !MODULAR
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
#else
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true, Mandatory = true)]
[System.Management.Automation.AllowEmptyString]
[System.Management.Automation.AllowNull]
#endif
[Amazon.PowerShell.Common.AWSRequiredParameter]
public System.String ResourceId { get; set; }
#endregion
#region Parameter PredefinedMetricSpecification_ResourceLabel
/// <summary>
/// <para>
/// <para>Identifies the resource associated with the metric type. You can't specify a resource
/// label unless the metric type is <code>ALBRequestCountPerTarget</code> and there is
/// a target group attached to the Spot Fleet request or ECS service.</para><para>The format is app/<load-balancer-name>/<load-balancer-id>/targetgroup/<target-group-name>/<target-group-id>,
/// where:</para><ul><li><para>app/<load-balancer-name>/<load-balancer-id> is the final portion of the
/// load balancer ARN</para></li><li><para>targetgroup/<target-group-name>/<target-group-id> is the final portion
/// of the target group ARN.</para></li></ul>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
[Alias("TargetTrackingScalingPolicyConfiguration_PredefinedMetricSpecification_ResourceLabel")]
public System.String PredefinedMetricSpecification_ResourceLabel { get; set; }
#endregion
#region Parameter ScalableDimension
/// <summary>
/// <para>
/// <para>The scalable dimension. This string consists of the service namespace, resource type,
/// and scaling property.</para><ul><li><para><code>ecs:service:DesiredCount</code> - The desired task count of an ECS service.</para></li><li><para><code>ec2:spot-fleet-request:TargetCapacity</code> - The target capacity of a Spot
/// Fleet request.</para></li><li><para><code>elasticmapreduce:instancegroup:InstanceCount</code> - The instance count of
/// an EMR Instance Group.</para></li><li><para><code>appstream:fleet:DesiredCapacity</code> - The desired capacity of an AppStream
/// 2.0 fleet.</para></li><li><para><code>dynamodb:table:ReadCapacityUnits</code> - The provisioned read capacity for
/// a DynamoDB table.</para></li><li><para><code>dynamodb:table:WriteCapacityUnits</code> - The provisioned write capacity for
/// a DynamoDB table.</para></li><li><para><code>dynamodb:index:ReadCapacityUnits</code> - The provisioned read capacity for
/// a DynamoDB global secondary index.</para></li><li><para><code>dynamodb:index:WriteCapacityUnits</code> - The provisioned write capacity for
/// a DynamoDB global secondary index.</para></li><li><para><code>rds:cluster:ReadReplicaCount</code> - The count of Aurora Replicas in an Aurora
/// DB cluster. Available for Aurora MySQL-compatible edition and Aurora PostgreSQL-compatible
/// edition.</para></li><li><para><code>sagemaker:variant:DesiredInstanceCount</code> - The number of EC2 instances
/// for an Amazon SageMaker model endpoint variant.</para></li><li><para><code>custom-resource:ResourceType:Property</code> - The scalable dimension for a
/// custom resource provided by your own application or service.</para></li><li><para><code>comprehend:document-classifier-endpoint:DesiredInferenceUnits</code> - The
/// number of inference units for an Amazon Comprehend document classification endpoint.</para></li><li><para><code>lambda:function:ProvisionedConcurrency</code> - The provisioned concurrency
/// for a Lambda function.</para></li></ul>
/// </para>
/// </summary>
#if !MODULAR
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
#else
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true, Mandatory = true)]
[System.Management.Automation.AllowNull]
#endif
[Amazon.PowerShell.Common.AWSRequiredParameter]
[AWSConstantClassSource("Amazon.ApplicationAutoScaling.ScalableDimension")]
public Amazon.ApplicationAutoScaling.ScalableDimension ScalableDimension { get; set; }
#endregion
#region Parameter TargetTrackingScalingPolicyConfiguration_ScaleInCooldown
/// <summary>
/// <para>
/// <para>The amount of time, in seconds, after a scale-in activity completes before another
/// scale in activity can start.</para><para>The cooldown period is used to block subsequent scale-in requests until it has expired.
/// The intention is to scale in conservatively to protect your application's availability.
/// However, if another alarm triggers a scale-out policy during the cooldown period after
/// a scale-in, Application Auto Scaling scales out your scalable target immediately.</para>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public System.Int32? TargetTrackingScalingPolicyConfiguration_ScaleInCooldown { get; set; }
#endregion
#region Parameter TargetTrackingScalingPolicyConfiguration_ScaleOutCooldown
/// <summary>
/// <para>
/// <para>The amount of time, in seconds, after a scale-out activity completes before another
/// scale-out activity can start.</para><para>While the cooldown period is in effect, the capacity that has been added by the previous
/// scale-out event that initiated the cooldown is calculated as part of the desired capacity
/// for the next scale out. The intention is to continuously (but not excessively) scale
/// out.</para>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public System.Int32? TargetTrackingScalingPolicyConfiguration_ScaleOutCooldown { get; set; }
#endregion
#region Parameter ServiceNamespace
/// <summary>
/// <para>
/// <para>The namespace of the AWS service that provides the resource or <code>custom-resource</code>
/// for a resource provided by your own application or service. For more information,
/// see <a href="http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html#genref-aws-service-namespaces">AWS
/// Service Namespaces</a> in the <i>Amazon Web Services General Reference</i>.</para>
/// </para>
/// </summary>
#if !MODULAR
[System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true)]
#else
[System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true, Mandatory = true)]
[System.Management.Automation.AllowNull]
#endif
[Amazon.PowerShell.Common.AWSRequiredParameter]
[AWSConstantClassSource("Amazon.ApplicationAutoScaling.ServiceNamespace")]
public Amazon.ApplicationAutoScaling.ServiceNamespace ServiceNamespace { get; set; }
#endregion
#region Parameter CustomizedMetricSpecification_Statistic
/// <summary>
/// <para>
/// <para>The statistic of the metric.</para>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
[Alias("TargetTrackingScalingPolicyConfiguration_CustomizedMetricSpecification_Statistic")]
[AWSConstantClassSource("Amazon.ApplicationAutoScaling.MetricStatistic")]
public Amazon.ApplicationAutoScaling.MetricStatistic CustomizedMetricSpecification_Statistic { get; set; }
#endregion
#region Parameter StepScalingPolicyConfiguration_StepAdjustment
/// <summary>
/// <para>
/// <para>A set of adjustments that enable you to scale based on the size of the alarm breach.</para>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
[Alias("StepScalingPolicyConfiguration_StepAdjustments")]
public Amazon.ApplicationAutoScaling.Model.StepAdjustment[] StepScalingPolicyConfiguration_StepAdjustment { get; set; }
#endregion
#region Parameter TargetTrackingScalingPolicyConfiguration_TargetValue
/// <summary>
/// <para>
/// <para>The target value for the metric. The range is 8.515920e-109 to 1.174271e+108 (Base
/// 10) or 2e-360 to 2e360 (Base 2).</para>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public System.Double? TargetTrackingScalingPolicyConfiguration_TargetValue { get; set; }
#endregion
#region Parameter CustomizedMetricSpecification_Unit
/// <summary>
/// <para>
/// <para>The unit of the metric.</para>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
[Alias("TargetTrackingScalingPolicyConfiguration_CustomizedMetricSpecification_Unit")]
public System.String CustomizedMetricSpecification_Unit { get; set; }
#endregion
#region Parameter Select
/// <summary>
/// Use the -Select parameter to control the cmdlet output. The default value is '*'.
/// Specifying -Select '*' will result in the cmdlet returning the whole service response (Amazon.ApplicationAutoScaling.Model.PutScalingPolicyResponse).
/// Specifying the name of a property of type Amazon.ApplicationAutoScaling.Model.PutScalingPolicyResponse will result in that property being returned.
/// Specifying -Select '^ParameterName' will result in the cmdlet returning the selected cmdlet parameter value.
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public string Select { get; set; } = "*";
#endregion
#region Parameter PassThru
/// <summary>
/// Changes the cmdlet behavior to return the value passed to the ServiceNamespace parameter.
/// The -PassThru parameter is deprecated, use -Select '^ServiceNamespace' instead. This parameter will be removed in a future version.
/// </summary>
[System.Obsolete("The -PassThru parameter is deprecated, use -Select '^ServiceNamespace' instead. This parameter will be removed in a future version.")]
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public SwitchParameter PassThru { get; set; }
#endregion
#region Parameter Force
/// <summary>
/// This parameter overrides confirmation prompts to force
/// the cmdlet to continue its operation. This parameter should always
/// be used with caution.
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public SwitchParameter Force { get; set; }
#endregion
protected override void ProcessRecord()
{
base.ProcessRecord();
var resourceIdentifiersText = FormatParameterValuesForConfirmationMsg(nameof(this.PolicyName), MyInvocation.BoundParameters);
if (!ConfirmShouldProceed(this.Force.IsPresent, resourceIdentifiersText, "Set-AASScalingPolicy (PutScalingPolicy)"))
{
return;
}
var context = new CmdletContext();
// allow for manipulation of parameters prior to loading into context
PreExecutionContextLoad(context);
#pragma warning disable CS0618, CS0612 //A class member was marked with the Obsolete attribute
if (ParameterWasBound(nameof(this.Select)))
{
context.Select = CreateSelectDelegate<Amazon.ApplicationAutoScaling.Model.PutScalingPolicyResponse, SetAASScalingPolicyCmdlet>(Select) ??
throw new System.ArgumentException("Invalid value for -Select parameter.", nameof(this.Select));
if (this.PassThru.IsPresent)
{
throw new System.ArgumentException("-PassThru cannot be used when -Select is specified.", nameof(this.Select));
}
}
else if (this.PassThru.IsPresent)
{
context.Select = (response, cmdlet) => this.ServiceNamespace;
}
#pragma warning restore CS0618, CS0612 //A class member was marked with the Obsolete attribute
context.PolicyName = this.PolicyName;
#if MODULAR
if (this.PolicyName == null && ParameterWasBound(nameof(this.PolicyName)))
{
WriteWarning("You are passing $null as a value for parameter PolicyName which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues.");
}
#endif
context.PolicyType = this.PolicyType;
context.ResourceId = this.ResourceId;
#if MODULAR
if (this.ResourceId == null && ParameterWasBound(nameof(this.ResourceId)))
{
WriteWarning("You are passing $null as a value for parameter ResourceId which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues.");
}
#endif
context.ScalableDimension = this.ScalableDimension;
#if MODULAR
if (this.ScalableDimension == null && ParameterWasBound(nameof(this.ScalableDimension)))
{
WriteWarning("You are passing $null as a value for parameter ScalableDimension which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues.");
}
#endif
context.ServiceNamespace = this.ServiceNamespace;
#if MODULAR
if (this.ServiceNamespace == null && ParameterWasBound(nameof(this.ServiceNamespace)))
{
WriteWarning("You are passing $null as a value for parameter ServiceNamespace which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues.");
}
#endif
context.StepScalingPolicyConfiguration_AdjustmentType = this.StepScalingPolicyConfiguration_AdjustmentType;
context.StepScalingPolicyConfiguration_Cooldown = this.StepScalingPolicyConfiguration_Cooldown;
context.StepScalingPolicyConfiguration_MetricAggregationType = this.StepScalingPolicyConfiguration_MetricAggregationType;
context.StepScalingPolicyConfiguration_MinAdjustmentMagnitude = this.StepScalingPolicyConfiguration_MinAdjustmentMagnitude;
if (this.StepScalingPolicyConfiguration_StepAdjustment != null)
{
context.StepScalingPolicyConfiguration_StepAdjustment = new List<Amazon.ApplicationAutoScaling.Model.StepAdjustment>(this.StepScalingPolicyConfiguration_StepAdjustment);
}
if (this.CustomizedMetricSpecification_Dimension != null)
{
context.CustomizedMetricSpecification_Dimension = new List<Amazon.ApplicationAutoScaling.Model.MetricDimension>(this.CustomizedMetricSpecification_Dimension);
}
context.CustomizedMetricSpecification_MetricName = this.CustomizedMetricSpecification_MetricName;
context.CustomizedMetricSpecification_Namespace = this.CustomizedMetricSpecification_Namespace;
context.CustomizedMetricSpecification_Statistic = this.CustomizedMetricSpecification_Statistic;
context.CustomizedMetricSpecification_Unit = this.CustomizedMetricSpecification_Unit;
context.TargetTrackingScalingPolicyConfiguration_DisableScaleIn = this.TargetTrackingScalingPolicyConfiguration_DisableScaleIn;
context.PredefinedMetricSpecification_PredefinedMetricType = this.PredefinedMetricSpecification_PredefinedMetricType;
context.PredefinedMetricSpecification_ResourceLabel = this.PredefinedMetricSpecification_ResourceLabel;
context.TargetTrackingScalingPolicyConfiguration_ScaleInCooldown = this.TargetTrackingScalingPolicyConfiguration_ScaleInCooldown;
context.TargetTrackingScalingPolicyConfiguration_ScaleOutCooldown = this.TargetTrackingScalingPolicyConfiguration_ScaleOutCooldown;
context.TargetTrackingScalingPolicyConfiguration_TargetValue = this.TargetTrackingScalingPolicyConfiguration_TargetValue;
// allow further manipulation of loaded context prior to processing
PostExecutionContextLoad(context);
var output = Execute(context) as CmdletOutput;
ProcessOutput(output);
}
#region IExecutor Members
public object Execute(ExecutorContext context)
{
var cmdletContext = context as CmdletContext;
// create request
var request = new Amazon.ApplicationAutoScaling.Model.PutScalingPolicyRequest();
if (cmdletContext.PolicyName != null)
{
request.PolicyName = cmdletContext.PolicyName;
}
if (cmdletContext.PolicyType != null)
{
request.PolicyType = cmdletContext.PolicyType;
}
if (cmdletContext.ResourceId != null)
{
request.ResourceId = cmdletContext.ResourceId;
}
if (cmdletContext.ScalableDimension != null)
{
request.ScalableDimension = cmdletContext.ScalableDimension;
}
if (cmdletContext.ServiceNamespace != null)
{
request.ServiceNamespace = cmdletContext.ServiceNamespace;
}
// populate StepScalingPolicyConfiguration
var requestStepScalingPolicyConfigurationIsNull = true;
request.StepScalingPolicyConfiguration = new Amazon.ApplicationAutoScaling.Model.StepScalingPolicyConfiguration();
Amazon.ApplicationAutoScaling.AdjustmentType requestStepScalingPolicyConfiguration_stepScalingPolicyConfiguration_AdjustmentType = null;
if (cmdletContext.StepScalingPolicyConfiguration_AdjustmentType != null)
{
requestStepScalingPolicyConfiguration_stepScalingPolicyConfiguration_AdjustmentType = cmdletContext.StepScalingPolicyConfiguration_AdjustmentType;
}
if (requestStepScalingPolicyConfiguration_stepScalingPolicyConfiguration_AdjustmentType != null)
{
request.StepScalingPolicyConfiguration.AdjustmentType = requestStepScalingPolicyConfiguration_stepScalingPolicyConfiguration_AdjustmentType;
requestStepScalingPolicyConfigurationIsNull = false;
}
System.Int32? requestStepScalingPolicyConfiguration_stepScalingPolicyConfiguration_Cooldown = null;
if (cmdletContext.StepScalingPolicyConfiguration_Cooldown != null)
{
requestStepScalingPolicyConfiguration_stepScalingPolicyConfiguration_Cooldown = cmdletContext.StepScalingPolicyConfiguration_Cooldown.Value;
}
if (requestStepScalingPolicyConfiguration_stepScalingPolicyConfiguration_Cooldown != null)
{
request.StepScalingPolicyConfiguration.Cooldown = requestStepScalingPolicyConfiguration_stepScalingPolicyConfiguration_Cooldown.Value;
requestStepScalingPolicyConfigurationIsNull = false;
}
Amazon.ApplicationAutoScaling.MetricAggregationType requestStepScalingPolicyConfiguration_stepScalingPolicyConfiguration_MetricAggregationType = null;
if (cmdletContext.StepScalingPolicyConfiguration_MetricAggregationType != null)
{
requestStepScalingPolicyConfiguration_stepScalingPolicyConfiguration_MetricAggregationType = cmdletContext.StepScalingPolicyConfiguration_MetricAggregationType;
}
if (requestStepScalingPolicyConfiguration_stepScalingPolicyConfiguration_MetricAggregationType != null)
{
request.StepScalingPolicyConfiguration.MetricAggregationType = requestStepScalingPolicyConfiguration_stepScalingPolicyConfiguration_MetricAggregationType;
requestStepScalingPolicyConfigurationIsNull = false;
}
System.Int32? requestStepScalingPolicyConfiguration_stepScalingPolicyConfiguration_MinAdjustmentMagnitude = null;
if (cmdletContext.StepScalingPolicyConfiguration_MinAdjustmentMagnitude != null)
{
requestStepScalingPolicyConfiguration_stepScalingPolicyConfiguration_MinAdjustmentMagnitude = cmdletContext.StepScalingPolicyConfiguration_MinAdjustmentMagnitude.Value;
}
if (requestStepScalingPolicyConfiguration_stepScalingPolicyConfiguration_MinAdjustmentMagnitude != null)
{
request.StepScalingPolicyConfiguration.MinAdjustmentMagnitude = requestStepScalingPolicyConfiguration_stepScalingPolicyConfiguration_MinAdjustmentMagnitude.Value;
requestStepScalingPolicyConfigurationIsNull = false;
}
List<Amazon.ApplicationAutoScaling.Model.StepAdjustment> requestStepScalingPolicyConfiguration_stepScalingPolicyConfiguration_StepAdjustment = null;
if (cmdletContext.StepScalingPolicyConfiguration_StepAdjustment != null)
{
requestStepScalingPolicyConfiguration_stepScalingPolicyConfiguration_StepAdjustment = cmdletContext.StepScalingPolicyConfiguration_StepAdjustment;
}
if (requestStepScalingPolicyConfiguration_stepScalingPolicyConfiguration_StepAdjustment != null)
{
request.StepScalingPolicyConfiguration.StepAdjustments = requestStepScalingPolicyConfiguration_stepScalingPolicyConfiguration_StepAdjustment;
requestStepScalingPolicyConfigurationIsNull = false;
}
// determine if request.StepScalingPolicyConfiguration should be set to null
if (requestStepScalingPolicyConfigurationIsNull)
{
request.StepScalingPolicyConfiguration = null;
}
// populate TargetTrackingScalingPolicyConfiguration
var requestTargetTrackingScalingPolicyConfigurationIsNull = true;
request.TargetTrackingScalingPolicyConfiguration = new Amazon.ApplicationAutoScaling.Model.TargetTrackingScalingPolicyConfiguration();
System.Boolean? requestTargetTrackingScalingPolicyConfiguration_targetTrackingScalingPolicyConfiguration_DisableScaleIn = null;
if (cmdletContext.TargetTrackingScalingPolicyConfiguration_DisableScaleIn != null)
{
requestTargetTrackingScalingPolicyConfiguration_targetTrackingScalingPolicyConfiguration_DisableScaleIn = cmdletContext.TargetTrackingScalingPolicyConfiguration_DisableScaleIn.Value;
}
if (requestTargetTrackingScalingPolicyConfiguration_targetTrackingScalingPolicyConfiguration_DisableScaleIn != null)
{
request.TargetTrackingScalingPolicyConfiguration.DisableScaleIn = requestTargetTrackingScalingPolicyConfiguration_targetTrackingScalingPolicyConfiguration_DisableScaleIn.Value;
requestTargetTrackingScalingPolicyConfigurationIsNull = false;
}
System.Int32? requestTargetTrackingScalingPolicyConfiguration_targetTrackingScalingPolicyConfiguration_ScaleInCooldown = null;
if (cmdletContext.TargetTrackingScalingPolicyConfiguration_ScaleInCooldown != null)
{
requestTargetTrackingScalingPolicyConfiguration_targetTrackingScalingPolicyConfiguration_ScaleInCooldown = cmdletContext.TargetTrackingScalingPolicyConfiguration_ScaleInCooldown.Value;
}
if (requestTargetTrackingScalingPolicyConfiguration_targetTrackingScalingPolicyConfiguration_ScaleInCooldown != null)
{
request.TargetTrackingScalingPolicyConfiguration.ScaleInCooldown = requestTargetTrackingScalingPolicyConfiguration_targetTrackingScalingPolicyConfiguration_ScaleInCooldown.Value;
requestTargetTrackingScalingPolicyConfigurationIsNull = false;
}
System.Int32? requestTargetTrackingScalingPolicyConfiguration_targetTrackingScalingPolicyConfiguration_ScaleOutCooldown = null;
if (cmdletContext.TargetTrackingScalingPolicyConfiguration_ScaleOutCooldown != null)
{
requestTargetTrackingScalingPolicyConfiguration_targetTrackingScalingPolicyConfiguration_ScaleOutCooldown = cmdletContext.TargetTrackingScalingPolicyConfiguration_ScaleOutCooldown.Value;
}
if (requestTargetTrackingScalingPolicyConfiguration_targetTrackingScalingPolicyConfiguration_ScaleOutCooldown != null)
{
request.TargetTrackingScalingPolicyConfiguration.ScaleOutCooldown = requestTargetTrackingScalingPolicyConfiguration_targetTrackingScalingPolicyConfiguration_ScaleOutCooldown.Value;
requestTargetTrackingScalingPolicyConfigurationIsNull = false;
}
System.Double? requestTargetTrackingScalingPolicyConfiguration_targetTrackingScalingPolicyConfiguration_TargetValue = null;
if (cmdletContext.TargetTrackingScalingPolicyConfiguration_TargetValue != null)
{
requestTargetTrackingScalingPolicyConfiguration_targetTrackingScalingPolicyConfiguration_TargetValue = cmdletContext.TargetTrackingScalingPolicyConfiguration_TargetValue.Value;
}
if (requestTargetTrackingScalingPolicyConfiguration_targetTrackingScalingPolicyConfiguration_TargetValue != null)
{
request.TargetTrackingScalingPolicyConfiguration.TargetValue = requestTargetTrackingScalingPolicyConfiguration_targetTrackingScalingPolicyConfiguration_TargetValue.Value;
requestTargetTrackingScalingPolicyConfigurationIsNull = false;
}
Amazon.ApplicationAutoScaling.Model.PredefinedMetricSpecification requestTargetTrackingScalingPolicyConfiguration_targetTrackingScalingPolicyConfiguration_PredefinedMetricSpecification = null;
// populate PredefinedMetricSpecification
var requestTargetTrackingScalingPolicyConfiguration_targetTrackingScalingPolicyConfiguration_PredefinedMetricSpecificationIsNull = true;
requestTargetTrackingScalingPolicyConfiguration_targetTrackingScalingPolicyConfiguration_PredefinedMetricSpecification = new Amazon.ApplicationAutoScaling.Model.PredefinedMetricSpecification();
Amazon.ApplicationAutoScaling.MetricType requestTargetTrackingScalingPolicyConfiguration_targetTrackingScalingPolicyConfiguration_PredefinedMetricSpecification_predefinedMetricSpecification_PredefinedMetricType = null;
if (cmdletContext.PredefinedMetricSpecification_PredefinedMetricType != null)
{
requestTargetTrackingScalingPolicyConfiguration_targetTrackingScalingPolicyConfiguration_PredefinedMetricSpecification_predefinedMetricSpecification_PredefinedMetricType = cmdletContext.PredefinedMetricSpecification_PredefinedMetricType;
}
if (requestTargetTrackingScalingPolicyConfiguration_targetTrackingScalingPolicyConfiguration_PredefinedMetricSpecification_predefinedMetricSpecification_PredefinedMetricType != null)
{
requestTargetTrackingScalingPolicyConfiguration_targetTrackingScalingPolicyConfiguration_PredefinedMetricSpecification.PredefinedMetricType = requestTargetTrackingScalingPolicyConfiguration_targetTrackingScalingPolicyConfiguration_PredefinedMetricSpecification_predefinedMetricSpecification_PredefinedMetricType;
requestTargetTrackingScalingPolicyConfiguration_targetTrackingScalingPolicyConfiguration_PredefinedMetricSpecificationIsNull = false;
}
System.String requestTargetTrackingScalingPolicyConfiguration_targetTrackingScalingPolicyConfiguration_PredefinedMetricSpecification_predefinedMetricSpecification_ResourceLabel = null;
if (cmdletContext.PredefinedMetricSpecification_ResourceLabel != null)
{
requestTargetTrackingScalingPolicyConfiguration_targetTrackingScalingPolicyConfiguration_PredefinedMetricSpecification_predefinedMetricSpecification_ResourceLabel = cmdletContext.PredefinedMetricSpecification_ResourceLabel;
}
if (requestTargetTrackingScalingPolicyConfiguration_targetTrackingScalingPolicyConfiguration_PredefinedMetricSpecification_predefinedMetricSpecification_ResourceLabel != null)
{
requestTargetTrackingScalingPolicyConfiguration_targetTrackingScalingPolicyConfiguration_PredefinedMetricSpecification.ResourceLabel = requestTargetTrackingScalingPolicyConfiguration_targetTrackingScalingPolicyConfiguration_PredefinedMetricSpecification_predefinedMetricSpecification_ResourceLabel;
requestTargetTrackingScalingPolicyConfiguration_targetTrackingScalingPolicyConfiguration_PredefinedMetricSpecificationIsNull = false;
}
// determine if requestTargetTrackingScalingPolicyConfiguration_targetTrackingScalingPolicyConfiguration_PredefinedMetricSpecification should be set to null
if (requestTargetTrackingScalingPolicyConfiguration_targetTrackingScalingPolicyConfiguration_PredefinedMetricSpecificationIsNull)
{
requestTargetTrackingScalingPolicyConfiguration_targetTrackingScalingPolicyConfiguration_PredefinedMetricSpecification = null;
}
if (requestTargetTrackingScalingPolicyConfiguration_targetTrackingScalingPolicyConfiguration_PredefinedMetricSpecification != null)
{
request.TargetTrackingScalingPolicyConfiguration.PredefinedMetricSpecification = requestTargetTrackingScalingPolicyConfiguration_targetTrackingScalingPolicyConfiguration_PredefinedMetricSpecification;
requestTargetTrackingScalingPolicyConfigurationIsNull = false;
}
Amazon.ApplicationAutoScaling.Model.CustomizedMetricSpecification requestTargetTrackingScalingPolicyConfiguration_targetTrackingScalingPolicyConfiguration_CustomizedMetricSpecification = null;
// populate CustomizedMetricSpecification
var requestTargetTrackingScalingPolicyConfiguration_targetTrackingScalingPolicyConfiguration_CustomizedMetricSpecificationIsNull = true;
requestTargetTrackingScalingPolicyConfiguration_targetTrackingScalingPolicyConfiguration_CustomizedMetricSpecification = new Amazon.ApplicationAutoScaling.Model.CustomizedMetricSpecification();
List<Amazon.ApplicationAutoScaling.Model.MetricDimension> requestTargetTrackingScalingPolicyConfiguration_targetTrackingScalingPolicyConfiguration_CustomizedMetricSpecification_customizedMetricSpecification_Dimension = null;
if (cmdletContext.CustomizedMetricSpecification_Dimension != null)
{
requestTargetTrackingScalingPolicyConfiguration_targetTrackingScalingPolicyConfiguration_CustomizedMetricSpecification_customizedMetricSpecification_Dimension = cmdletContext.CustomizedMetricSpecification_Dimension;
}
if (requestTargetTrackingScalingPolicyConfiguration_targetTrackingScalingPolicyConfiguration_CustomizedMetricSpecification_customizedMetricSpecification_Dimension != null)
{
requestTargetTrackingScalingPolicyConfiguration_targetTrackingScalingPolicyConfiguration_CustomizedMetricSpecification.Dimensions = requestTargetTrackingScalingPolicyConfiguration_targetTrackingScalingPolicyConfiguration_CustomizedMetricSpecification_customizedMetricSpecification_Dimension;
requestTargetTrackingScalingPolicyConfiguration_targetTrackingScalingPolicyConfiguration_CustomizedMetricSpecificationIsNull = false;
}
System.String requestTargetTrackingScalingPolicyConfiguration_targetTrackingScalingPolicyConfiguration_CustomizedMetricSpecification_customizedMetricSpecification_MetricName = null;
if (cmdletContext.CustomizedMetricSpecification_MetricName != null)
{
requestTargetTrackingScalingPolicyConfiguration_targetTrackingScalingPolicyConfiguration_CustomizedMetricSpecification_customizedMetricSpecification_MetricName = cmdletContext.CustomizedMetricSpecification_MetricName;
}
if (requestTargetTrackingScalingPolicyConfiguration_targetTrackingScalingPolicyConfiguration_CustomizedMetricSpecification_customizedMetricSpecification_MetricName != null)
{
requestTargetTrackingScalingPolicyConfiguration_targetTrackingScalingPolicyConfiguration_CustomizedMetricSpecification.MetricName = requestTargetTrackingScalingPolicyConfiguration_targetTrackingScalingPolicyConfiguration_CustomizedMetricSpecification_customizedMetricSpecification_MetricName;
requestTargetTrackingScalingPolicyConfiguration_targetTrackingScalingPolicyConfiguration_CustomizedMetricSpecificationIsNull = false;
}
System.String requestTargetTrackingScalingPolicyConfiguration_targetTrackingScalingPolicyConfiguration_CustomizedMetricSpecification_customizedMetricSpecification_Namespace = null;
if (cmdletContext.CustomizedMetricSpecification_Namespace != null)
{
requestTargetTrackingScalingPolicyConfiguration_targetTrackingScalingPolicyConfiguration_CustomizedMetricSpecification_customizedMetricSpecification_Namespace = cmdletContext.CustomizedMetricSpecification_Namespace;
}
if (requestTargetTrackingScalingPolicyConfiguration_targetTrackingScalingPolicyConfiguration_CustomizedMetricSpecification_customizedMetricSpecification_Namespace != null)
{
requestTargetTrackingScalingPolicyConfiguration_targetTrackingScalingPolicyConfiguration_CustomizedMetricSpecification.Namespace = requestTargetTrackingScalingPolicyConfiguration_targetTrackingScalingPolicyConfiguration_CustomizedMetricSpecification_customizedMetricSpecification_Namespace;
requestTargetTrackingScalingPolicyConfiguration_targetTrackingScalingPolicyConfiguration_CustomizedMetricSpecificationIsNull = false;
}
Amazon.ApplicationAutoScaling.MetricStatistic requestTargetTrackingScalingPolicyConfiguration_targetTrackingScalingPolicyConfiguration_CustomizedMetricSpecification_customizedMetricSpecification_Statistic = null;
if (cmdletContext.CustomizedMetricSpecification_Statistic != null)
{
requestTargetTrackingScalingPolicyConfiguration_targetTrackingScalingPolicyConfiguration_CustomizedMetricSpecification_customizedMetricSpecification_Statistic = cmdletContext.CustomizedMetricSpecification_Statistic;
}
if (requestTargetTrackingScalingPolicyConfiguration_targetTrackingScalingPolicyConfiguration_CustomizedMetricSpecification_customizedMetricSpecification_Statistic != null)
{
requestTargetTrackingScalingPolicyConfiguration_targetTrackingScalingPolicyConfiguration_CustomizedMetricSpecification.Statistic = requestTargetTrackingScalingPolicyConfiguration_targetTrackingScalingPolicyConfiguration_CustomizedMetricSpecification_customizedMetricSpecification_Statistic;
requestTargetTrackingScalingPolicyConfiguration_targetTrackingScalingPolicyConfiguration_CustomizedMetricSpecificationIsNull = false;
}
System.String requestTargetTrackingScalingPolicyConfiguration_targetTrackingScalingPolicyConfiguration_CustomizedMetricSpecification_customizedMetricSpecification_Unit = null;
if (cmdletContext.CustomizedMetricSpecification_Unit != null)
{
requestTargetTrackingScalingPolicyConfiguration_targetTrackingScalingPolicyConfiguration_CustomizedMetricSpecification_customizedMetricSpecification_Unit = cmdletContext.CustomizedMetricSpecification_Unit;
}
if (requestTargetTrackingScalingPolicyConfiguration_targetTrackingScalingPolicyConfiguration_CustomizedMetricSpecification_customizedMetricSpecification_Unit != null)
{
requestTargetTrackingScalingPolicyConfiguration_targetTrackingScalingPolicyConfiguration_CustomizedMetricSpecification.Unit = requestTargetTrackingScalingPolicyConfiguration_targetTrackingScalingPolicyConfiguration_CustomizedMetricSpecification_customizedMetricSpecification_Unit;
requestTargetTrackingScalingPolicyConfiguration_targetTrackingScalingPolicyConfiguration_CustomizedMetricSpecificationIsNull = false;
}
// determine if requestTargetTrackingScalingPolicyConfiguration_targetTrackingScalingPolicyConfiguration_CustomizedMetricSpecification should be set to null
if (requestTargetTrackingScalingPolicyConfiguration_targetTrackingScalingPolicyConfiguration_CustomizedMetricSpecificationIsNull)
{
requestTargetTrackingScalingPolicyConfiguration_targetTrackingScalingPolicyConfiguration_CustomizedMetricSpecification = null;
}
if (requestTargetTrackingScalingPolicyConfiguration_targetTrackingScalingPolicyConfiguration_CustomizedMetricSpecification != null)
{
request.TargetTrackingScalingPolicyConfiguration.CustomizedMetricSpecification = requestTargetTrackingScalingPolicyConfiguration_targetTrackingScalingPolicyConfiguration_CustomizedMetricSpecification;
requestTargetTrackingScalingPolicyConfigurationIsNull = false;
}
// determine if request.TargetTrackingScalingPolicyConfiguration should be set to null
if (requestTargetTrackingScalingPolicyConfigurationIsNull)
{
request.TargetTrackingScalingPolicyConfiguration = null;
}
CmdletOutput output;
// issue call
var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint);
try
{
var response = CallAWSServiceOperation(client, request);
object pipelineOutput = null;
pipelineOutput = cmdletContext.Select(response, this);
output = new CmdletOutput
{
PipelineOutput = pipelineOutput,
ServiceResponse = response
};
}
catch (Exception e)
{
output = new CmdletOutput { ErrorResponse = e };
}
return output;
}
public ExecutorContext CreateContext()
{
return new CmdletContext();
}
#endregion
#region AWS Service Operation Call
private Amazon.ApplicationAutoScaling.Model.PutScalingPolicyResponse CallAWSServiceOperation(IAmazonApplicationAutoScaling client, Amazon.ApplicationAutoScaling.Model.PutScalingPolicyRequest request)
{
Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "Application Auto Scaling", "PutScalingPolicy");
try
{
#if DESKTOP
return client.PutScalingPolicy(request);
#elif CORECLR
return client.PutScalingPolicyAsync(request).GetAwaiter().GetResult();
#else
#error "Unknown build edition"
#endif
}
catch (AmazonServiceException exc)
{
var webException = exc.InnerException as System.Net.WebException;
if (webException != null)
{
throw new Exception(Utils.Common.FormatNameResolutionFailureMessage(client.Config, webException.Message), webException);
}
throw;
}
}
#endregion
internal partial class CmdletContext : ExecutorContext
{
public System.String PolicyName { get; set; }
public Amazon.ApplicationAutoScaling.PolicyType PolicyType { get; set; }
public System.String ResourceId { get; set; }
public Amazon.ApplicationAutoScaling.ScalableDimension ScalableDimension { get; set; }
public Amazon.ApplicationAutoScaling.ServiceNamespace ServiceNamespace { get; set; }
public Amazon.ApplicationAutoScaling.AdjustmentType StepScalingPolicyConfiguration_AdjustmentType { get; set; }
public System.Int32? StepScalingPolicyConfiguration_Cooldown { get; set; }
public Amazon.ApplicationAutoScaling.MetricAggregationType StepScalingPolicyConfiguration_MetricAggregationType { get; set; }
public System.Int32? StepScalingPolicyConfiguration_MinAdjustmentMagnitude { get; set; }
public List<Amazon.ApplicationAutoScaling.Model.StepAdjustment> StepScalingPolicyConfiguration_StepAdjustment { get; set; }
public List<Amazon.ApplicationAutoScaling.Model.MetricDimension> CustomizedMetricSpecification_Dimension { get; set; }
public System.String CustomizedMetricSpecification_MetricName { get; set; }
public System.String CustomizedMetricSpecification_Namespace { get; set; }
public Amazon.ApplicationAutoScaling.MetricStatistic CustomizedMetricSpecification_Statistic { get; set; }
public System.String CustomizedMetricSpecification_Unit { get; set; }
public System.Boolean? TargetTrackingScalingPolicyConfiguration_DisableScaleIn { get; set; }
public Amazon.ApplicationAutoScaling.MetricType PredefinedMetricSpecification_PredefinedMetricType { get; set; }
public System.String PredefinedMetricSpecification_ResourceLabel { get; set; }
public System.Int32? TargetTrackingScalingPolicyConfiguration_ScaleInCooldown { get; set; }
public System.Int32? TargetTrackingScalingPolicyConfiguration_ScaleOutCooldown { get; set; }
public System.Double? TargetTrackingScalingPolicyConfiguration_TargetValue { get; set; }
public System.Func<Amazon.ApplicationAutoScaling.Model.PutScalingPolicyResponse, SetAASScalingPolicyCmdlet, object> Select { get; set; } =
(response, cmdlet) => response;
}
}
}
| 71.431791 | 491 | 0.725094 | [
"Apache-2.0"
] | JekzVadaria/aws-tools-for-powershell | modules/AWSPowerShell/Cmdlets/ApplicationAutoScaling/Basic/Set-AASScalingPolicy-Cmdlet.cs | 60,221 | C# |
using System.ComponentModel.DataAnnotations.Schema;
namespace AkshaySDemoModels.PostgreSQL
{
[Table("recipes")]
public class Recipe
{
[Column("id")]
public int ID { get; set; }
[Column("name")]
public string Name { get; set; }
[Column("description")]
public string Description { get; set; }
[Column("comment")]
public string Comment { get; set; }
[Column("creatorsname")]
public string CreatorsName { get; set; }
[Column("notes")]
public string Notes { get; set; }
}
}
/* Azure SQL Table DDL
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Recipes](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](max) NULL,
[Description] [nvarchar](max) NULL,
CONSTRAINT [PK_Recipes] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
ALTER TABLE [dbo].[Recipes] ADD [Comment] VARCHAR(max) NULL
GO
*/
| 22.254902 | 168 | 0.644053 | [
"Apache-2.0"
] | akshays2112/AkshaySDemo | AkshaySDemoModels/PostgreSQL/Recipe.cs | 1,137 | C# |
using System.Threading.Tasks;
namespace privatetestrunner.shared.interfaces
{
public interface ITestRunner
{
Task Run();
}
} | 16.111111 | 45 | 0.689655 | [
"MIT"
] | keyoke/AzureApplicationInsights | PrivateAvailabilityTests/src/privatetestrunner.shared/interfaces/ITestRunner.cs | 145 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace pjank.BossaAPI.DTO
{
/// <summary>
/// Obiekt transportowy do przekazywania (między modułami biblioteki)
/// podstawowych danych nt. konkretnego rachunku klienta.
/// </summary>
public class AccountData
{
public string Number;
public Paper[] Papers;
public decimal AvailableCash;
public decimal AvailableFunds;
public decimal? DepositValue;
public decimal? DepositBlocked;
public decimal? DepositDeficit;
public decimal PortfolioValue;
}
}
| 24.375 | 71 | 0.731624 | [
"Apache-2.0"
] | L-Sypniewski/bossa-api.net | BossaAPI/src/Networking/DTO/AccountData.cs | 589 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApp1.PalindromicPrime
{
public abstract class BasePalindromicPrimePrinter
{
public abstract void PrintNumbers();
}
}
| 18.583333 | 53 | 0.748879 | [
"MIT"
] | shervinmontajam/PalindromicPrime | ConsoleApp1/PalindromicPrime/BasePalindromicPrimePrinter.cs | 225 | C# |
using System;
using System.Linq;
class Program
{
static void Main(string[] args)
{
int[] arr = Console.ReadLine().Split(' ').Select(x => int.Parse(x)).ToArray();
for (int i = 0; i < arr.Length-1; i++)
{
int count = 0;
for (int j = i+1; j < arr.Length; j++)
{
if (arr[i]>arr[j])
{
count++;
}
else
{
break;
}
}
if (count==arr.Length-i-1)
{
Console.Write(arr[i]+" ");
}
}
Console.Write(arr[arr.Length-1]);
Console.WriteLine();
}
}
| 21.882353 | 86 | 0.348118 | [
"MIT"
] | aalishov/SoftUni | 02-C-Sharp-Fundamentals---May-2019/03. CSharp-Fundamentals-Arrays-Exercises/05. Top Integers/Program.cs | 746 | C# |
namespace Elders.Hystrix.NET.Example
{
using System;
using System.Globalization;
using System.Threading;
using Hystrix.NET.MetricsEventStream;
internal class CurrentTimeBackgroundWorker : StoppableBackgroundWorker
{
private const string ThreadName = "Hystrix-Example-Worker-{0}";
private static readonly log4net.ILog Logger = log4net.LogManager.GetLogger(typeof(CurrentTimeBackgroundWorker));
private static int nextId = 1;
public CurrentTimeBackgroundWorker()
: base(string.Format(CultureInfo.InvariantCulture, ThreadName, nextId++))
{
}
protected override void DoWork()
{
while (true)
{
bool shouldStop = this.SleepAndGetShouldStop(TimeSpan.FromSeconds(1.0));
if (shouldStop)
{
break;
}
GetCurrentTimeCommand command = new GetCurrentTimeCommand();
long currentTime = command.Execute();
Logger.Debug(string.Format(CultureInfo.InvariantCulture, "The current time is {0}.", currentTime));
}
}
}
}
| 31.131579 | 120 | 0.606932 | [
"Apache-2.0"
] | Elders/Hystrix.NET | src/Elders.Hystrix.NET.Example/CurrentTimeBackgroundWorker.cs | 1,185 | C# |
namespace Gecko.WebIDL
{
using System;
internal class MozContactChangeEvent : WebIDLBase
{
public MozContactChangeEvent(nsIDOMWindow globalWindow, nsISupports thisObject) :
base(globalWindow, thisObject)
{
}
public string ContactID
{
get
{
return this.GetProperty<string>("contactID");
}
}
public string Reason
{
get
{
return this.GetProperty<string>("reason");
}
}
}
}
| 19.870968 | 90 | 0.465909 | [
"MIT"
] | haga-rak/Freezer | Freezer/GeckoFX/__Core/WebIDL/Generated/MozContactChangeEvent.cs | 616 | C# |
////////////////////////////////////////////////////////////////////////
// Copyright (c) 2011-2016 by Rob Jellinghaus. //
// All Rights Reserved. //
////////////////////////////////////////////////////////////////////////
using Holofunk.Core;
using System;
using System.Windows.Forms;
using Un4seen.Bass;
namespace Holofunk
{
/// <summary>
/// A BASS push stream together with the effects affecting it.
/// </summary>
/// <remarks>
/// Holofunk precreates and pools these in order to avoid expensive BASS_VST_ChannelSetDSP calls
/// from the BASS thread.
/// </remarks>
public class BassStream
{
readonly int m_idUniqueWithinPool;
/// <summary>BASS HSTREAM to the stream of this track</summary>
readonly StreamHandle m_streamHandle;
/// <summary>The effects applied to this track's push stream</summary>
readonly EffectSet m_effects;
public BassStream(int idUniqueWithinPool, Form baseForm)
{
m_idUniqueWithinPool = idUniqueWithinPool;
m_streamHandle = (StreamHandle)Bass.BASS_StreamCreatePush(
Clock.TimepointRateHz,
HolofunkBassAsio.InputChannelCount,
BASSFlag.BASS_SAMPLE_FLOAT | BASSFlag.BASS_STREAM_DECODE,
new IntPtr(m_idUniqueWithinPool));
m_effects = AllEffects.CreateLoopEffectSet(m_streamHandle, baseForm);
}
public int IdUniqueWithinPool { get { return m_idUniqueWithinPool; } }
public StreamHandle PushStream { get { return m_streamHandle; } }
public EffectSet Effects { get { return m_effects; } }
}
}
| 35.875 | 100 | 0.580139 | [
"MIT"
] | RobJellinghaus/Holofunk | HolofunkBass/BassStream.cs | 1,724 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Content.Server.GameObjects.EntitySystems;
using Content.Shared.GameObjects;
using Robust.Server.GameObjects.Components.Container;
using Robust.Server.Interfaces.GameObjects;
using Robust.Server.Interfaces.Player;
using Robust.Shared.GameObjects;
using Robust.Shared.Interfaces.GameObjects;
using Robust.Shared.Interfaces.GameObjects.Components;
using Robust.Shared.Interfaces.Network;
using Robust.Shared.IoC;
using Robust.Shared.Utility;
using Robust.Shared.ViewVariables;
using static Content.Shared.GameObjects.Components.Inventory.EquipmentSlotDefines;
using static Content.Shared.GameObjects.SharedInventoryComponent.ClientInventoryMessage;
using IComponent = Robust.Shared.Interfaces.GameObjects.IComponent;
namespace Content.Server.GameObjects
{
[RegisterComponent]
public class InventoryComponent : SharedInventoryComponent
{
#pragma warning disable 649
[Dependency] private readonly IEntitySystemManager _entitySystemManager;
#pragma warning restore 649
[ViewVariables]
private readonly Dictionary<Slots, ContainerSlot> SlotContainers = new Dictionary<Slots, ContainerSlot>();
public override void Initialize()
{
base.Initialize();
foreach (var slotName in InventoryInstance.SlotMasks)
{
if (slotName != Slots.NONE)
{
AddSlot(slotName);
}
}
}
public override void OnRemove()
{
var slots = SlotContainers.Keys.ToList();
foreach (var slot in slots)
{
RemoveSlot(slot);
}
base.OnRemove();
}
/// <summary>
/// Helper to get container name for specified slot on this component
/// </summary>
/// <param name="slot"></param>
/// <returns></returns>
private string GetSlotString(Slots slot)
{
return Name + "_" + Enum.GetName(typeof(Slots), slot);
}
/// <summary>
/// Gets the clothing equipped to the specified slot.
/// </summary>
/// <param name="slot">The slot to get the item for.</param>
/// <returns>Null if the slot is empty, otherwise the item.</returns>
public ItemComponent GetSlotItem(Slots slot)
{
return GetSlotItem<ItemComponent>(slot);
}
public T GetSlotItem<T>(Slots slot) where T : ItemComponent
{
return SlotContainers[slot].ContainedEntity?.GetComponent<T>();
}
public bool TryGetSlotItem<T>(Slots slot, out T itemComponent) where T : ItemComponent
{
itemComponent = GetSlotItem<T>(slot);
return itemComponent != null;
}
/// <summary>
/// Equips slothing to the specified slot.
/// </summary>
/// <remarks>
/// This will fail if there is already an item in the specified slot.
/// </remarks>
/// <param name="slot">The slot to put the item in.</param>
/// <param name="clothing">The item to insert into the slot.</param>
/// <returns>True if the item was successfully inserted, false otherwise.</returns>
public bool Equip(Slots slot, ClothingComponent clothing)
{
if (clothing == null)
{
throw new ArgumentNullException(nameof(clothing),
"Clothing must be passed here. To remove some clothing from a slot, use Unequip()");
}
if (clothing.SlotFlags == SlotFlags.PREVENTEQUIP //Flag to prevent equipping at all
|| (clothing.SlotFlags & SlotMasks[slot]) == 0
) //Does the clothing flag have any of our requested slot flags
{
return false;
}
var inventorySlot = SlotContainers[slot];
if (!inventorySlot.Insert(clothing.Owner))
{
return false;
}
clothing.EquippedToSlot();
Dirty();
return true;
}
/// <summary>
/// Checks whether an item can be put in the specified slot.
/// </summary>
/// <param name="slot">The slot to check for.</param>
/// <param name="item">The item to check for.</param>
/// <returns>True if the item can be inserted into the specified slot.</returns>
public bool CanEquip(Slots slot, ClothingComponent item)
{
return SlotContainers[slot].CanInsert(item.Owner);
}
/// <summary>
/// Drops the item in a slot.
/// </summary>
/// <param name="slot">The slot to drop the item from.</param>
/// <returns>True if an item was dropped, false otherwise.</returns>
public bool Unequip(Slots slot)
{
if (!CanUnequip(slot))
{
return false;
}
var inventorySlot = SlotContainers[slot];
var item = inventorySlot.ContainedEntity.GetComponent<ItemComponent>();
if (!inventorySlot.Remove(inventorySlot.ContainedEntity))
{
return false;
}
item.RemovedFromSlot();
// TODO: The item should be dropped to the container our owner is in, if any.
var itemTransform = item.Owner.GetComponent<ITransformComponent>();
itemTransform.GridPosition = Owner.GetComponent<ITransformComponent>().GridPosition;
Dirty();
return true;
}
/// <summary>
/// Checks whether an item can be dropped from the specified slot.
/// </summary>
/// <param name="slot">The slot to check for.</param>
/// <returns>
/// True if there is an item in the slot and it can be dropped, false otherwise.
/// </returns>
public bool CanUnequip(Slots slot)
{
var InventorySlot = SlotContainers[slot];
return InventorySlot.ContainedEntity != null && InventorySlot.CanRemove(InventorySlot.ContainedEntity);
}
/// <summary>
/// Adds a new slot to this inventory component.
/// </summary>
/// <param name="slot">The name of the slot to add.</param>
/// <exception cref="InvalidOperationException">
/// Thrown if the slot with specified name already exists.
/// </exception>
public ContainerSlot AddSlot(Slots slot)
{
if (HasSlot(slot))
{
throw new InvalidOperationException($"Slot '{slot}' already exists.");
}
Dirty();
return SlotContainers[slot] = ContainerManagerComponent.Create<ContainerSlot>(GetSlotString(slot), Owner);
}
/// <summary>
/// Removes a slot from this inventory component.
/// </summary>
/// <remarks>
/// If the slot contains an item, the item is dropped.
/// </remarks>
/// <param name="slot">The name of the slot to remove.</param>
public void RemoveSlot(Slots slot)
{
if (!HasSlot(slot))
{
throw new InvalidOperationException($"Slow '{slot}' does not exist.");
}
if (GetSlotItem(slot) != null && !Unequip(slot))
{
// TODO: Handle this potential failiure better.
throw new InvalidOperationException(
"Unable to remove slot as the contained clothing could not be dropped");
}
SlotContainers.Remove(slot);
Dirty();
}
/// <summary>
/// Checks whether a slot with the specified name exists.
/// </summary>
/// <param name="slot">The slot name to check.</param>
/// <returns>True if the slot exists, false otherwise.</returns>
public bool HasSlot(Slots slot)
{
return SlotContainers.ContainsKey(slot);
}
/// <summary>
/// The underlying Container System just notified us that an entity was removed from it.
/// We need to make sure we process that removed entity as being unequpped from the slot.
/// </summary>
private void ForceUnequip(IContainer container, IEntity entity)
{
// make sure this is one of our containers.
// Technically the correct way would be to enumerate the possible slot names
// comparing with this container, but I might as well put the dictionary to good use.
if (!(container is ContainerSlot slot) || !SlotContainers.ContainsValue(slot))
return;
if (entity.TryGetComponent(out ItemComponent itemComp))
itemComp.RemovedFromSlot();
Dirty();
}
/// <summary>
/// Message that tells us to equip or unequip items from the inventory slots
/// </summary>
/// <param name="msg"></param>
private void HandleInventoryMessage(ClientInventoryMessage msg)
{
switch (msg.Updatetype)
{
case ClientInventoryUpdate.Equip:
{
var hands = Owner.GetComponent<HandsComponent>();
var activeHand = hands.GetActiveHand;
if (activeHand != null && activeHand.Owner.TryGetComponent(out ClothingComponent clothing))
{
hands.Drop(hands.ActiveIndex);
if (!Equip(msg.Inventoryslot, clothing))
{
hands.PutInHand(clothing);
}
}
break;
}
case ClientInventoryUpdate.Use:
{
var interactionSystem = _entitySystemManager.GetEntitySystem<InteractionSystem>();
var hands = Owner.GetComponent<HandsComponent>();
var activeHand = hands.GetActiveHand;
var itemContainedInSlot = GetSlotItem(msg.Inventoryslot);
if (itemContainedInSlot != null)
{
if (activeHand != null)
{
interactionSystem.Interaction(Owner, activeHand.Owner, itemContainedInSlot.Owner,
new Robust.Shared.Map.GridCoordinates());
}
else if (Unequip(msg.Inventoryslot))
{
hands.PutInHand(itemContainedInSlot);
}
}
break;
}
}
}
/// <inheritdoc />
public override void HandleMessage(ComponentMessage message, INetChannel netChannel = null,
IComponent component = null)
{
base.HandleMessage(message, netChannel, component);
switch (message)
{
case ClientInventoryMessage msg:
var playerMan = IoCManager.Resolve<IPlayerManager>();
var session = playerMan.GetSessionByChannel(netChannel);
var playerentity = session.AttachedEntity;
if (playerentity == Owner)
HandleInventoryMessage(msg);
break;
case OpenSlotStorageUIMessage msg:
if (!HasSlot(msg.Slot)) // client input sanitization
return;
var item = GetSlotItem(msg.Slot);
if (item != null && item.Owner.TryGetComponent(out ServerStorageComponent storage))
storage.OpenStorageUI(Owner);
break;
case ContainerContentsModifiedMessage msg:
if (msg.Removed)
ForceUnequip(msg.Container, msg.Entity);
break;
}
}
public override ComponentState GetComponentState()
{
var list = new List<KeyValuePair<Slots, EntityUid>>();
foreach (var (slot, container) in SlotContainers)
{
if (container.ContainedEntity != null)
{
list.Add(new KeyValuePair<Slots, EntityUid>(slot, container.ContainedEntity.Uid));
}
}
return new InventoryComponentState(list);
}
}
}
| 37.705357 | 118 | 0.551504 | [
"MIT"
] | rjarbour/space-station-14 | Content.Server/GameObjects/Components/GUI/InventoryComponent.cs | 12,671 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using IdentityServer4.Contrib.HttpClientService.Infrastructure.IdentityServer.Interfaces;
using IdentityServer4.Contrib.HttpClientService.Infrastructure.IdentityServer.Models;
namespace IdentityServer4.Contrib.HttpClientService.Infrastructure.IdentityServer
{
/// <summary>
/// Selects the correct <see cref="IIdentityServerHttpClient"/> based on <see cref="IIdentityServerOptions"/>.
/// </summary>
public class IdentityServerHttpClientSelector : IIdentityServerHttpClientSelector
{
private IEnumerable<IIdentityServerHttpClient> _httpClients;
/// <summary>
/// Constructor of the <see cref="IdentityServerHttpClientSelector"/>.
/// </summary>
public IdentityServerHttpClientSelector(IEnumerable<IIdentityServerHttpClient> httpClients)
{
_httpClients = httpClients;
}
/// <summary>
/// Finds the appropriate implementation of <see cref="IIdentityServerHttpClient"/> based on the <paramref name="options"/>.
/// </summary>
/// <param name="options">The <paramref name="options"/> for retrieving an access token.</param>
/// <returns>An <see cref="IIdentityServerHttpClient"/>.</returns>
public IIdentityServerHttpClient Get(IIdentityServerOptions options)
{
if (!_httpClients.Any(x => x.HttpClientOptionsType.IsAssignableFrom(options.GetType())))
{
throw new InvalidOperationException("There is no assignable type for the options selected. " +
"Does your options inherit from either " + nameof(ClientCredentialsOptions) + " or " + nameof(PasswordOptions) + "?");
}
return _httpClients.First(x => x.HttpClientOptionsType.IsAssignableFrom(options.GetType()));
}
}
} | 44.690476 | 138 | 0.690464 | [
"Apache-2.0"
] | SteffenHeidrich/IdentityServer4.Contrib.HttpClientService | src/IdentityServer4.Contrib.HttpClientService/Infrastructure/IdentityServer/IdentityServerHttpClientSelector.cs | 1,879 | C# |
using AgateLib.Display;
using AgateLib.Mathematics.Geometry;
using AgateLib.Demo.Fakes;
using AgateLib.UserInterface.Content;
using FluentAssertions;
using Microsoft.Xna.Framework;
using Moq;
using System.Linq;
using Xunit;
namespace AgateLib.UserInterface.Widgets
{
public class LabelTest
{
private readonly FakeFontCore fontCore;
private readonly Font font;
private readonly FontProvider fontProvider;
private readonly ContentLayoutEngine contentLayout;
private readonly Mock<ICanvas> canvas;
private readonly Mock<IUserInterfaceRenderContext> context;
private readonly Mock<IDisplaySystem> displaySystem;
public LabelTest()
{
fontCore = new FakeFontCore("default");
font = new Font(fontCore);
fontProvider = new FontProvider
{
{ "default", font }
};
contentLayout = new ContentLayoutEngine(fontProvider);
canvas = new Mock<ICanvas>();
context = CommonMocks.RenderContext(contentLayout, canvas.Object);
canvas.Setup(x => x.Draw(It.IsAny<IContentLayout>(), It.IsAny<Vector2>()))
.Callback<IContentLayout, Vector2>((content, dest) =>
{
content.Draw(dest);
});
displaySystem = CommonMocks.DisplaySystem(fontProvider);
}
[Fact]
public void LabelBasicTextNoWrap()
{
string text = "These aren't the droids you're looking for.";
int expectedWidth = 215;
int expectedHeight = 10;
var label = new Label(new LabelProps { Text = text }) { AppContext = new UserInterfaceAppContext() };
var labelElement = (LabelElement)label.FinalizeRendering(null);
labelElement.Display.System = displaySystem.Object;
labelElement.Style.Update(1);
Size idealSize = labelElement.CalcIdealContentSize(context.Object, new Size(1000, 1000));
labelElement.Draw(context.Object, new Rectangle(40, 60, 1000, 1000));
labelElement.Props.Text.Should().Be(text);
idealSize.Width.Should().Be(expectedWidth);
idealSize.Height.Should().Be(expectedHeight);
fontCore.DrawCalls.Count.Should().Be(7);
string[] words = text.Split(' ');
Vector2 dest = new Vector2(40, 60);
for (int i = 0; i < words.Length; i++)
{
var drawCall = fontCore.DrawCalls[i];
drawCall.Text.Should().Be(words[i]);
drawCall.Parameters.Should().Match(p => p == null || p.Count() == 0);
drawCall.Color.Should().Be(Color.White);
drawCall.Dest.Should().Be(dest);
// add 1 for the space after the word.
dest.X += 5 * (1 + words[i].Length);
}
}
[Fact]
public void LabelBasicTextWithCarriageReturn()
{
string text = "This has a carriage\nreturn.";
int expectedWidth = 95;
int expectedHeight = 20;
var label = new Label(new LabelProps { Text = text }) { AppContext = new UserInterfaceAppContext() };
var labelElement = (LabelElement)label.FinalizeRendering(null);
labelElement.Display.System = displaySystem.Object;
labelElement.Style.Update(1);
Size idealSize = labelElement.CalcIdealContentSize(context.Object, new Size(1000, 1000));
labelElement.Draw(context.Object, new Rectangle(40, 60, 1000, 1000));
labelElement.Props.Text.Should().Be(text);
idealSize.Width.Should().Be(expectedWidth);
idealSize.Height.Should().Be(expectedHeight);
fontCore.DrawCalls.Count.Should().Be(5);
var firstDraw = fontCore.DrawCalls[0];
var secondDraw = fontCore.DrawCalls[4];
firstDraw.Text.Should().Be("This");
firstDraw.Parameters.Should().Match(p => p == null || p.Count() == 0);
firstDraw.Color.Should().Be(Color.White);
firstDraw.Dest.Should().Be(new Vector2(40, 60));
secondDraw.Text.Should().Be("return.");
secondDraw.Parameters.Should().Match(p => p == null || p.Count() == 0);
secondDraw.Color.Should().Be(Color.White);
secondDraw.Dest.Should().Be(new Vector2(40, 70));
}
}
}
| 36.120968 | 113 | 0.590534 | [
"MIT"
] | eylvisaker/AgateLib | tests/AgateLib.UnitTests/UserInterface/Widgets/LabelTest.cs | 4,481 | C# |
// Copyright (c) Josef Pihrt. All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Immutable;
using System.Composition;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Roslynator.CodeFixes;
namespace Roslynator.CSharp.CodeFixes
{
[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(DocumentCodeFixProvider))]
[Shared]
public sealed class DocumentCodeFixProvider : BaseCodeFixProvider
{
public override ImmutableArray<string> FixableDiagnosticIds
{
get { return ImmutableArray.Create(DiagnosticIdentifiers.RemoveFileWithNoCode); }
}
public override FixAllProvider GetFixAllProvider()
{
return null;
}
public override Task RegisterCodeFixesAsync(CodeFixContext context)
{
foreach (Diagnostic diagnostic in context.Diagnostics)
{
switch (diagnostic.Id)
{
case DiagnosticIdentifiers.RemoveFileWithNoCode:
{
CodeAction codeAction = CodeAction.Create(
"Remove file with no code",
cancellationToken =>
{
cancellationToken.ThrowIfCancellationRequested();
return RemoveFromSolutionAsync(context.Document);
},
GetEquivalenceKey(diagnostic));
context.RegisterCodeFix(codeAction, diagnostic);
break;
}
}
}
return Task.CompletedTask;
}
public static Task<Solution> RemoveFromSolutionAsync(Document document)
{
return Task.FromResult(document.Solution().RemoveDocument(document.Id));
}
}
}
| 36.016949 | 160 | 0.578353 | [
"Apache-2.0"
] | PrimoDev23/Roslynator | src/Analyzers.CodeFixes/CSharp/CodeFixes/DocumentCodeFixProvider.cs | 2,127 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FishAI : MonoBehaviour
{
[SerializeField]
private float speed;
public bool moveRight;
public bool caught;
public bool released;
void Start()
{
caught = false;
}
void Update()
{
//This is checking if the fish has been caught by the player or not, if it has then the fish will stop it's movement functions.
if (!caught)
{
//Checking if the moveRight bool is true or not. this will automatically move the fish to the right if it's true but if not then it should flip and go back the other way.
if (moveRight)
{
transform.localScale = new Vector3(transform.localScale.x * -1, transform.localScale.y, transform.localScale.z);
transform.Translate(-2 * Time.deltaTime * speed, 0, 0);
transform.localScale = new Vector2(1, 1);
}
else
{
transform.Translate(2 * Time.deltaTime * speed, 0, 0);
transform.localScale = new Vector2(-1, 1);
}
}
}
//This is a simple flip function that will flip the sprite to make the fish turn around by changing the local scale.
private void Flip()
{
if (moveRight)
{
transform.localScale = new Vector3(transform.localScale.x * -1, transform.localScale.y, transform.localScale.z);
}
if (!moveRight)
{
transform.localScale = new Vector3(transform.localScale.x * 1, transform.localScale.y, transform.localScale.z);
}
}
private void OnTriggerEnter2D(Collider2D other)
{
//This checks for the game border and should flip the fish around but doesn't seem to be working which is a problem.
if (other.gameObject.CompareTag("Border"))
{
if (moveRight)
{
moveRight = false;
}
else
{
moveRight = true;
}
}
}
//I use this to give the fish a slight delay after being released before it's destroyed. I would add a nice animation here of it swimming away if I could animate.
public IEnumerator ReleasedTimer()
{
yield return new WaitForSeconds(2);
Destroy(this.gameObject);
}
}
| 31.61039 | 182 | 0.58258 | [
"MIT"
] | JBroughton2/COMP140Controller | COMP140ControllerGame/Assets/Scripts/FishAI.cs | 2,436 | C# |
using Microsoft.EntityFrameworkCore;
namespace GensouSakuya.Aria2.Desktop.Model
{
public class DbContext:Microsoft.EntityFrameworkCore.DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder builder)
{
base.OnConfiguring(builder);
builder.UseSqlite("Data Source = data.db;");
builder.EnableSensitiveDataLogging();
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
}
public DbSet<DownloadTask> DownloadTasks { get; set; }
}
}
| 27.727273 | 78 | 0.662295 | [
"MIT"
] | GensouSakuya/aria2-desktop | src/GensouSakuya.Aria2.Desktop.Model/DbContext.cs | 612 | C# |
using Crowdin.Api.Core.Converters;
using JetBrains.Annotations;
namespace Crowdin.Api.Reports
{
[PublicAPI]
[StrictStringRepresentation]
public enum ReportCurrency
{
USD,
EUR,
JPY,
GBP,
AUD,
CAD,
CHF,
CNY,
SEK,
NZD,
MXN,
SGD,
HKD,
NOK,
KRW,
TRY,
RUB,
INR,
BRL,
ZAR,
GEL,
UAH
}
} | 14.029412 | 34 | 0.429769 | [
"MIT"
] | crowdin/crowdin-api-client-dotnet | src/Crowdin.Api/Reports/ReportCurrency.cs | 479 | C# |
using System;
using NUnit.Framework;
namespace XSerializer.Tests
{
public class JsonMiscellaneousTypesTests
{
[Test]
public void CanSerializeEnum()
{
var serializer = new JsonSerializer<Foo1>();
var foo = new Foo1 { Bar = Garply.Fred };
var json = serializer.Serialize(foo);
Assert.That(json, Is.EqualTo(@"{""Bar"":""Fred""}"));
}
[Test]
public void CanDeserializeEnum()
{
var serializer = new JsonSerializer<Foo1>();
var json = @"{""Bar"":""Fred""}";
var foo = serializer.Deserialize(json);
Assert.That(foo.Bar, Is.EqualTo(Garply.Fred));
}
[TestCase(Garply.Fred, @"""Fred""")]
[TestCase(null, "null")]
public void CanSerializeNullableEnum(Garply? barValue, string expectedBarValue)
{
var serializer = new JsonSerializer<Foo4>();
var foo = new Foo4 { Bar = barValue };
var json = serializer.Serialize(foo);
Assert.That(json, Is.EqualTo(@"{""Bar"":" + expectedBarValue + "}"));
}
[TestCase(@"""Fred""", Garply.Fred)]
[TestCase("null", null)]
public void CanDeserializeNullableEnum(string barValue, Garply? expectedBarValue)
{
var serializer = new JsonSerializer<Foo4>();
var json = @"{""Bar"":" + barValue + "}";
var foo = serializer.Deserialize(json);
Assert.That(foo.Bar, Is.EqualTo(expectedBarValue));
}
[Test]
public void CanSerializeType()
{
var serializer = new JsonSerializer<Foo3>();
var foo = new Foo3 { Bar = typeof(Foo3) };
var json = serializer.Serialize(foo);
Assert.That(json, Is.EqualTo($@"{{""Bar"":""XSerializer.Tests.JsonMiscellaneousTypesTests+Foo3, {typeof(Foo3).Assembly.GetName().Name}""}}"));
}
[Test]
public void CanDeserializeType()
{
var serializer = new JsonSerializer<Foo3>();
var json = $@"{{""Bar"":""{typeof(Foo3).AssemblyQualifiedName}""}}";
var foo = serializer.Deserialize(json);
Assert.That(foo.Bar, Is.EqualTo(typeof(Foo3)));
}
[Test]
public void CanSerializeUri()
{
var serializer = new JsonSerializer<Foo2>();
var foo = new Foo2 { Bar = new Uri("http://google.com/") };
var json = serializer.Serialize(foo);
Assert.That(json, Is.EqualTo(@"{""Bar"":""http:\/\/google.com\/""}"));
}
[Test]
public void CanDeserializeUri()
{
var serializer = new JsonSerializer<Foo2>();
var json = @"{""Bar"":""http:\/\/google.com\/""}";
var foo = serializer.Deserialize(json);
Assert.That(foo.Bar, Is.EqualTo(new Uri("http://google.com/")));
}
public class Foo1
{
public Garply Bar { get; set; }
}
public class Foo4
{
public Garply? Bar { get; set; }
}
public class Foo2
{
public Uri Bar { get; set; }
}
public class Foo3
{
public Type Bar { get; set; }
}
public enum Garply
{
Waldo,
Fred
}
}
} | 25.825758 | 154 | 0.512174 | [
"MIT"
] | QuickenLoans/XSerializer | XSerializer.Tests/JsonMiscellaneousTypesTests.cs | 3,409 | C# |
/*
* Copyright (c) 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://www.apache.org/licenses/LICENSE-2.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.
*/
namespace Amazon.IonObjectMapper
{
using Amazon.IonDotnet;
public class IonBigDecimalSerializer : IonSerializer<BigDecimal>
{
public override BigDecimal Deserialize(IIonReader reader)
{
return reader.DecimalValue();
}
public override void Serialize(IIonWriter writer, BigDecimal item)
{
writer.WriteDecimal(item);
}
}
}
| 32.096774 | 119 | 0.695477 | [
"Apache-2.0"
] | QPC-database/ion-object-mapper-dotnet | Amazon.IonObjectMapper/Serializer/Primitive/IonBigDecimalSerializer.cs | 997 | C# |
using System;
using System.Diagnostics;
using SalamanderWamp.Configuration;
using SalamanderWamp.UI;
using System.Windows.Controls;
using System.Windows.Media;
using System.ComponentModel;
using SalamanderWamp.Tool;
namespace SalamanderWamp.Programs
{
public class WampProgram: INotifyPropertyChanged
{
public TextBlock statusLabel { get; set; } // Label that shows the programs status
public string exeName { get; set; } // Location of the executable file
public string procName { get; set; } // Name of the process
public string progName { get; set; } // User-friendly name of the program
public string workingDir { get; set; } // working directory
public Log.LogSection progLogSection { get; set; } // LogSection of the program
public string startArgs { get; set; } // Start Arguments
public string stopArgs { get; set; } // Stop Arguments if KillStop is false
public bool killStop { get; set; } // Kill process instead of stopping it gracefully
public string confDir { get; set; } // Directory where all the programs configuration files are
public string logDir { get; set; } // Directory where all the programs log files are
public Ini Settings { get; set; }
protected string errOutput = null; // Output when start the process fail
public Process ps = new Process();
public event PropertyChangedEventHandler PropertyChanged;
// 是否在运行
private bool running = false;
public bool Running
{
get
{
return this.running;
}
set
{
this.running = value;
if(PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("Running"));
}
}
}
public WampProgram()
{
//configContextMenu = new ContextMenuStrip();
//logContextMenu = new ContextMenuStrip();
//configContextMenu.ItemClicked += configContextMenu_ItemClicked;
//logContextMenu.ItemClicked += logContextMenu_ItemClicked;
}
/// <summary>
/// 设置状态
/// </summary>
public void SetStatus()
{
if (this.IsRunning() == true)
{
this.Running = true;
}
else
{
this.Running = false;
}
}
public void StartProcess(string exe, string args, bool wait = false)
{
ps.StartInfo.FileName = exe;
ps.StartInfo.Arguments = args;
ps.StartInfo.UseShellExecute = false;
ps.StartInfo.RedirectStandardOutput = true;
ps.StartInfo.RedirectStandardError = true;
ps.ErrorDataReceived += Ps_ErrorDataReceived;
ps.StartInfo.WorkingDirectory = workingDir;
ps.StartInfo.CreateNoWindow = true;
ps.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
ps.Start();
if (wait) {
ps.WaitForExit();
}
}
/// <summary>
/// 启动进程出错触发
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Ps_ErrorDataReceived(object sender, DataReceivedEventArgs e)
{
errOutput = e.Data;
}
public virtual void Start()
{
if(IsRunning())
{
return;
}
try {
StartProcess(exeName, startArgs);
if(String.IsNullOrEmpty(errOutput))
{
Log.wnmp_log_notice("Started " + progName, progLogSection);
}
else
{
Log.wnmp_log_error("Failed: " + errOutput, progLogSection);
errOutput = null;
}
} catch (Exception ex) {
Log.wnmp_log_error("Start(): " + ex.Message, progLogSection);
}
}
public virtual void Stop()
{
if(!IsRunning())
{
return;
}
if (killStop == false)
StartProcess(exeName, stopArgs, true);
var processes = Process.GetProcessesByName(procName);
foreach (var process in processes) {
process.Kill();
}
Log.wnmp_log_notice("Stopped " + progName, progLogSection);
}
public void Restart()
{
this.Stop();
this.Start();
Log.wnmp_log_notice("Restarted " + progName, progLogSection);
}
/// <summary>
/// 判断程序是否运行
/// </summary>
/// <returns></returns>
public virtual bool IsRunning()
{
var processes = Process.GetProcessesByName(procName);
return (processes.Length != 0);
}
}
}
| 31.487654 | 106 | 0.526955 | [
"MIT"
] | salamander-mh/SalamanderWamp | SalamanderWamp/Programs/WampProgram.cs | 5,153 | C# |
// Copyright 2018 Esri.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific
// language governing permissions and limitations under the License.
using Esri.ArcGISRuntime;
using Esri.ArcGISRuntime.Mapping;
using System;
using Xamarin.Forms;
namespace ArcGISRuntime.Samples.ChangeTimeExtent
{
[ArcGISRuntime.Samples.Shared.Attributes.Sample(
"Change time extent",
"MapView",
"This sample demonstrates how to filter data in layers by applying a time extent to a MapView.",
"Switch between the available options and observe how the data is filtered.")]
public partial class ChangeTimeExtent : ContentPage
{
// Hold two map service URIs, one for use with an ArcGISMapImageLayer, the other for use with a FeatureLayer.
private readonly Uri _mapServerUri = new Uri("https://sampleserver6.arcgisonline.com/arcgis/rest/services/Hurricanes/MapServer");
private readonly Uri _featureLayerUri = new Uri("https://sampleserver6.arcgisonline.com/arcgis/rest/services/Earthquakes_Since1970/MapServer/0");
public ChangeTimeExtent()
{
InitializeComponent();
// Create the UI, setup the control references and execute initialization
Initialize();
}
private void Initialize()
{
// Create new Map with basemap and initial location.
Map map = new Map(Basemap.CreateTopographic());
// Assign the map to the MapView.
MyMapView.Map = map;
// Load the layers from the corresponding URIs.
ArcGISMapImageLayer imageryLayer = new ArcGISMapImageLayer(_mapServerUri);
FeatureLayer pointLayer = new FeatureLayer(_featureLayerUri);
// Add the layers to the map.
MyMapView.Map.OperationalLayers.Add(imageryLayer);
MyMapView.Map.OperationalLayers.Add(pointLayer);
}
private void twoThousand_Clicked(object sender, EventArgs e)
{
// Hard-coded start value: January 1st, 2000.
DateTime start = new DateTime(2000, 1, 1);
// Hard-coded end value: December 31st, 2000.
DateTime end = new DateTime(2000, 12, 31);
// Set the time extent on the map with the hard-coded values.
MyMapView.TimeExtent = new TimeExtent(start, end);
}
private void twoThousandFive_Clicked(object sender, EventArgs e)
{
// Hard-coded start value: January 1st, 2005.
DateTime start = new DateTime(2005, 1, 1);
// Hard-coded end value: December 31st, 2005.
DateTime end = new DateTime(2005, 12, 31);
// Set the time extent on the map with the hard-coded values.
MyMapView.TimeExtent = new TimeExtent(start, end);
}
}
} | 42.220779 | 153 | 0.665026 | [
"Apache-2.0"
] | ChrisFrenchPDX/arcgis-runtime-samples-dotnet | src/Forms/Shared/Samples/MapView/ChangeTimeExtent/ChangeTimeExtent.xaml.cs | 3,251 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace WebAppMvcFwork
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
}
| 25.208333 | 100 | 0.566942 | [
"MIT"
] | byrne8783/controlled | someComparisons/WebAppMvcFwork/App_Start/RouteConfig.cs | 607 | C# |
#region License
// Author: Roman Kravchik
// Based on HttpBasicAuthenticator class by John Sheehan
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.Linq;
namespace RestSharp.Authenticators
{
/// <summary>
/// JSON WEB TOKEN (JWT) Authenticator class.
/// <remarks>https://tools.ietf.org/html/draft-ietf-oauth-json-web-token</remarks>
/// </summary>
public class JwtAuthenticator : IAuthenticator
{
private readonly string authHeader;
public JwtAuthenticator(string accessToken)
{
if (accessToken == null)
{
throw new ArgumentNullException("accessToken");
}
this.authHeader = string.Format("Bearer {0}", accessToken);
}
public void Authenticate(IRestClient client, IRestRequest request)
{
// only add the Authorization parameter if it hasn't been added by a previous Execute
if (!request.Parameters.Any(p => p.Type.Equals(ParameterType.HttpHeader) &&
p.Name.Equals("Authorization", StringComparison.OrdinalIgnoreCase)))
{
request.AddParameter("Authorization", this.authHeader, ParameterType.HttpHeader);
}
}
}
}
| 34.148148 | 113 | 0.645879 | [
"Apache-2.0"
] | Arch/RestSharp | RestSharp/Authenticators/JwtAuthenticator.cs | 1,844 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace Ink.WebEnd.Controllers
{
[Route("api/[controller]")]
public class SampleDataController : Controller
{
private static string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
[HttpGet("[action]")]
public IEnumerable<WeatherForecast> WeatherForecasts()
{
var rng = new Random();
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
DateFormatted = DateTime.Now.AddDays(index).ToString("d"),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
});
}
public class WeatherForecast
{
public string DateFormatted { get; set; }
public int TemperatureC { get; set; }
public string Summary { get; set; }
public int TemperatureF
{
get
{
return 32 + (int)(TemperatureC / 0.5556);
}
}
}
}
}
| 28.533333 | 110 | 0.530374 | [
"MIT"
] | Officialjide/WhiteInk | Ink/Ink.WebEnd/Controllers/SampleDataController.cs | 1,284 | C# |
#if UNITY_INPUT_SYSTEM_ENABLE_XR || PACKAGE_DOCS_GENERATION
using System.Runtime.InteropServices;
using UnityEngine.InputSystem.Utilities;
using UnityEngine.InputSystem.LowLevel;
namespace UnityEngine.InputSystem.XR.Haptics
{
public struct HapticCapabilities
{
public HapticCapabilities(uint numChannels, uint frequencyHz, uint maxBufferSize)
{
this.numChannels = numChannels;
this.frequencyHz = frequencyHz;
this.maxBufferSize = maxBufferSize;
}
public uint numChannels { get; private set; }
public uint frequencyHz { get; private set; }
public uint maxBufferSize { get; private set; }
}
[StructLayout(LayoutKind.Explicit, Size = kSize)]
public struct GetHapticCapabilitiesCommand : IInputDeviceCommandInfo
{
static FourCC Type => new FourCC('X', 'H', 'C', '0');
const int kSize = InputDeviceCommand.kBaseCommandSize + sizeof(uint) * 3;
public FourCC typeStatic => Type;
[FieldOffset(0)]
InputDeviceCommand baseCommand;
[FieldOffset(InputDeviceCommand.kBaseCommandSize)]
public uint numChannels;
[FieldOffset(InputDeviceCommand.kBaseCommandSize + sizeof(uint))]
public uint frequencyHz;
[FieldOffset(InputDeviceCommand.kBaseCommandSize + (sizeof(uint) * 2))]
public uint maxBufferSize;
public HapticCapabilities capabilities => new HapticCapabilities(numChannels, frequencyHz, maxBufferSize);
public static GetHapticCapabilitiesCommand Create()
{
return new GetHapticCapabilitiesCommand
{
baseCommand = new InputDeviceCommand(Type, kSize),
};
}
}
}
#endif // UNITY_INPUT_SYSTEM_ENABLE_XR
| 32.436364 | 114 | 0.678251 | [
"MIT"
] | Axedas/hex-game | New Unity Project (1)/Library/PackageCache/com.unity.inputsystem@1.0.0/InputSystem/Plugins/XR/Haptics/GetHapticCapabilitiesCommand.cs | 1,784 | 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("SuperSocket.Common")]
[assembly: AssemblyDescription("SuperSocket.Common")]
[assembly: AssemblyConfiguration("")]
// 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("8056596a-0926-47ad-9f2f-6adad34fdba3")]
| 45.333333 | 84 | 0.786765 | [
"Apache-2.0"
] | ChuckFork/SuperSocket | Common/Properties/AssemblyInfo.cs | 818 | C# |
using System.Collections.Generic;
using System.Linq;
using AutoFixture;
using FluentAssertions;
using Frank.Libraries.Extensions;
using Xunit;
namespace Frank.Libraries.Tests.Extensions
{
public class EnumerableExtensionsTests
{
private readonly Fixture _fixture = new Fixture();
private readonly IEnumerable<string> _things;
public EnumerableExtensionsTests()
{
_things = _fixture.CreateMany<string>(100);
}
[Fact]
public void Batch_StateUnderTest_ExpectedBehavior()
{
// Arrange
var maxItems = 10;
// Act
var result = _things.Batch(maxItems);
// Assert
result.Should().HaveCount(10);
}
[Fact]
public void Random_StateUnderTest_ExpectedBehavior()
{
// Arrange
var results = new List<bool>();
// Act
for (int i = 0; i < 1024; i++)
{
var result = _things.Random();
results.Add(_things.Contains(result));
}
// Assert
results.Should().AllBeEquivalentTo(true);
}
}
} | 23.096154 | 60 | 0.549542 | [
"MIT"
] | stzoran1/Frank.Libraries | Frank.Libraries.Tests/Extensions/EnumerableExtensionsTests.cs | 1,203 | C# |
using TinyCsvParser.Mapping;
namespace Members.Scraper
{
public class CsvMemberMapping : CsvMapping<Member>
{
// 0. Customer ID
// 1. Name
// 2. Company / In Care Of
// 3. Addr L1
// 4. Addr L2
// 5. Addr L3
// 6. Addr L4
// 7. Addr L5
// 8. Country
// 9. Member has opted-out of Toastmasters WHQ marketing mail
// 10. Email
// 11. Secondary Email
// 12. Member has opted-out of Toastmasters WHQ marketing emails
// 13. Home Phone
// 14. Mobile Phone
// 15. Additional Phone
// 16. Member has opted-out of Toastmasters WHQ marketing phone calls
// 17. Paid Until
// 18. Member of Club Since
// 19. Original Join Date
// 20. status (*)
// 21. Current Position
// 22. Future Position
// 23. Pathways Enrolled
public CsvMemberMapping() : base()
{
MapProperty(0, x => x.ToastmastersId);
MapProperty(1, x => x.Name);
MapProperty(10, x => x.Email);
}
}
}
| 28.846154 | 77 | 0.518222 | [
"MIT"
] | FrancisGrignon/toastmasters-schedule | src/Functions/Members.Scraper/Members.Scraper/CsvMemberMapping.cs | 1,127 | C# |
using Iyzipay.Model;
using Iyzipay.Request;
using Iyzipay.Tests.Functional;
using Iyzipay.Tests.Functional.Builder.Request;
using NUnit.Framework;
namespace Iyzipay.Tests.Functional
{
public class CardManagementRetrieveCardTest : BaseTest
{
[SetUp]
public void SetUp()
{
Initialize();
_options.BaseUrl = "https://sandbox-cm.iyzipay.com";
}
[Test]
public void Should_Retrieve_Cards()
{
CreateCardManagementPageInitializeRequest initializeRequest = CardManagementPageRequestBuilder.Create().Build();
CardManagementPageInitialize cardManagementPageInitialize = CardManagementPageInitialize.Create(initializeRequest, _options);
RetrieveCardManagementPageCardRequest retrieveCardRequest = CardManagementRetrieveCardBuilder.Create()
.PageToken(cardManagementPageInitialize.Token)
.Build();
CardManagementPageCard cardManagementPageCard = CardManagementPageCard.Retrieve(retrieveCardRequest, _options);
PrintResponse(cardManagementPageCard);
Assert.AreEqual(Status.SUCCESS.ToString(), cardManagementPageCard.Status);
Assert.AreEqual(Locale.TR.ToString(), cardManagementPageCard.Locale);
Assert.Null(cardManagementPageCard.ErrorCode);
Assert.Null(cardManagementPageCard.ErrorMessage);
Assert.Null(cardManagementPageCard.ErrorGroup);
Assert.NotNull(cardManagementPageCard);
}
[Test]
public void Should_Not_Retrieve_Cards_When_PageToken_Is_Not_Exist()
{
RetrieveCardManagementPageCardRequest retrieveCardRequest = CardManagementRetrieveCardBuilder.Create()
.PageToken("pagetoken")
.Build();
CardManagementPageCard cardManagementPageCard = CardManagementPageCard.Retrieve(retrieveCardRequest, _options);
PrintResponse(cardManagementPageCard);
Assert.AreEqual(Status.FAILURE.ToString(), cardManagementPageCard.Status);
Assert.AreEqual("4002",cardManagementPageCard.ErrorCode);
Assert.AreEqual("Geçersiz token",cardManagementPageCard.ErrorMessage);
}
}
} | 42.462963 | 137 | 0.688181 | [
"MIT"
] | LazZiya/iyzipay-dotnet | Iyzipay.Tests/Functional/CardManagementRetrieveCardTest.cs | 2,294 | 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("CarDealer.Models")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CarDealer.Models")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("d9d985e0-7bf4-4b30-85a0-aee63e77ca7d")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.837838 | 84 | 0.747857 | [
"MIT"
] | mdamyanova/C-Sharp-Web-Development | 07.C# DB Fundamentals/07.02.Databases Advanced - Entity Framework/10.JSON Processing/CarDealer/CarDealer.Models/Properties/AssemblyInfo.cs | 1,403 | C# |
using System;
namespace DXFLib
{
[AttributeUsage(AttributeTargets.Property)]
class TableAttribute : Attribute
{
public string TableName;
public Type TableParser;
public TableAttribute(string name, Type parser)
{
this.TableName = name;
this.TableParser = parser;
}
}
}
| 18.526316 | 55 | 0.602273 | [
"MIT"
] | codingdna2/WPF-DXF-Viewer | DXFLib/TableAttribute.cs | 354 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// O código foi gerado por uma ferramenta.
// Versão de Tempo de Execução:4.0.30319.42000
//
// As alterações ao arquivo poderão causar comportamento incorreto e serão perdidas se
// o código for gerado novamente.
// </auto-generated>
//------------------------------------------------------------------------------
namespace SistemaVendas.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.3.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.SpecialSettingAttribute(global::System.Configuration.SpecialSetting.ConnectionString)]
[global::System.Configuration.DefaultSettingValueAttribute("Data Source=DESKTOP-628SFJB;Initial Catalog=SistemaVenda;Integrated Security=True" +
"")]
public string SistemaVendaConnectionString {
get {
return ((string)(this["SistemaVendaConnectionString"]));
}
}
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.SpecialSettingAttribute(global::System.Configuration.SpecialSetting.ConnectionString)]
[global::System.Configuration.DefaultSettingValueAttribute("Data Source=DESKTOP-H923SLO\\SQLEXPRESS;Initial Catalog=SistemaVenda;Integrated Se" +
"curity=True")]
public string SistemaVendaConnectionStringC {
get {
return ((string)(this["SistemaVendaConnectionStringC"]));
}
}
}
}
| 47.938776 | 153 | 0.645381 | [
"MIT"
] | lucasestevan/SistemaVendasC- | SistemaVendas/SistemaVendas/Properties/Settings.Designer.cs | 2,360 | C# |
using UnityEditor;
using UnityEngine;
namespace LongMan.GameUtil.Editors
{
/// <summary>
/// Original Source: https://github.com/upscalebaby/generic-serializable-dictionary
/// Draws the generic dictionary a bit nicer than Unity would natively (not as many expand-arrows
/// and better spacing between KeyValue pairs). Also renders a warning-box if there are duplicate
/// keys in the dictionary.
/// </summary>
[CustomPropertyDrawer(typeof(GenericDictionary<,>))]
public class GenericDictionaryPropertyDrawer : PropertyDrawer
{
static float lineHeight = EditorGUIUtility.singleLineHeight;
static float vertSpace = EditorGUIUtility.standardVerticalSpacing;
public override void OnGUI(Rect pos, SerializedProperty property, GUIContent label)
{
// Draw list.
var list = property.FindPropertyRelative("list");
string fieldName = ObjectNames.NicifyVariableName(fieldInfo.Name);
var currentRect = new Rect(lineHeight, pos.y, pos.width, lineHeight);
EditorGUI.PropertyField(currentRect, list, new GUIContent(fieldName), true);
// Draw key collision warning.
if (property.FindPropertyRelative("keyCollision").boolValue)
{
currentRect.y += EditorGUI.GetPropertyHeight(list, true) + vertSpace;
var entryPos = new Rect(lineHeight, currentRect.y, pos.width, lineHeight * 2f);
EditorGUI.HelpBox(entryPos, "Duplicate keys will not be serialized.", MessageType.Warning);
}
}
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
{
float totHeight = 0f;
// Height of KeyValue list.
var listProp = property.FindPropertyRelative("list");
totHeight += EditorGUI.GetPropertyHeight(listProp, true);
// Height of key collision warning.
if (property.FindPropertyRelative("keyCollision").boolValue)
totHeight += lineHeight * 2f + vertSpace;
return totHeight;
}
}
} | 42.84 | 107 | 0.657796 | [
"MIT"
] | Youngchangoon/GameUtil | Editor/GenericDictionaryPropertyDrawer.cs | 2,144 | C# |
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Mir.WorkServer.DependencyInjection.Orm
{
public class SqlSugarDbContextFactory : ISqlSugarDbContextFactory
{
private readonly IEnumerable<MirSqlSugarClient> _clients;
public SqlSugarDbContextFactory(IEnumerable<MirSqlSugarClient> clients)
{
_clients = clients;
}
public SqlSugarClient DbContext(string name = "Default")
{
if (name == null)
throw new ArgumentNullException(nameof(name));
MirSqlSugarClient dbContext;
if (name == "Default")
{
dbContext = _clients.ToList().Find(c => c.Default);
}
else
{
dbContext = _clients.FirstOrDefault(it => it.DbName.Equals(name, StringComparison.OrdinalIgnoreCase));
}
if (dbContext == null)
throw new ArgumentException("can not find a match dbcontext!");
return dbContext;
}
}
}
| 27.74359 | 118 | 0.592421 | [
"Apache-2.0"
] | miryuan/Mir.WorkServerTemplate | Mir.WorkServerTemplate/DependencyInjection/Orm/SqlSugarDbContextFactory.cs | 1,084 | C# |
namespace Sentry.Tests;
public class AppDomainProcessExitIntegrationTests
{
private class Fixture
{
public IHub Hub { get; set; } = Substitute.For<IHub, IDisposable>();
public IAppDomain AppDomain { get; set; } = Substitute.For<IAppDomain>();
public Fixture() => Hub.IsEnabled.Returns(true);
public AppDomainProcessExitIntegration GetSut() => new(AppDomain);
}
private readonly Fixture _fixture = new();
public SentryOptions SentryOptions { get; set; } = new();
[Fact]
public void Handle_WithException_CaptureEvent()
{
var sut = _fixture.GetSut();
sut.Register(_fixture.Hub, SentryOptions);
sut.HandleProcessExit(this, EventArgs.Empty);
(_fixture.Hub as IDisposable).Received(1).Dispose();
}
[Fact]
public void Register_ProcessExit_Subscribes()
{
var sut = _fixture.GetSut();
sut.Register(_fixture.Hub, SentryOptions);
_fixture.AppDomain.Received().ProcessExit += sut.HandleProcessExit;
}
[Fact]
public void Unregister_ProcessExit_Unsubscribes()
{
var sut = _fixture.GetSut();
sut.Register(_fixture.Hub, SentryOptions);
sut.Unregister(_fixture.Hub);
_fixture.AppDomain.Received(1).ProcessExit -= sut.HandleProcessExit;
}
}
| 25.980392 | 81 | 0.658868 | [
"MIT"
] | TawasalMessenger/sentry-dotnet | test/Sentry.Tests/AppDomainProcessExitIntegrationTests.cs | 1,325 | C# |
// Code generated by Microsoft (R) AutoRest Code Generator (autorest: 3.0.6365, generator: {generator})
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
namespace Commvault.Powershell.Models
{
using Commvault.Powershell.Runtime.PowerShell;
/// <summary>Dell EMC ECS (S3-compatible)</summary>
[System.ComponentModel.TypeConverter(typeof(DellEmcTypeConverter))]
public partial class DellEmc
{
/// <summary>
/// <c>AfterDeserializeDictionary</c> will be called after the deserialization has finished, allowing customization of the
/// object before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content);
/// <summary>
/// <c>AfterDeserializePSObject</c> will be called after the deserialization has finished, allowing customization of the object
/// before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content);
/// <summary>
/// <c>BeforeDeserializeDictionary</c> will be called before the deserialization has commenced, allowing complete customization
/// of the object before it is deserialized.
/// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
/// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow);
/// <summary>
/// <c>BeforeDeserializePSObject</c> will be called before the deserialization has commenced, allowing complete customization
/// of the object before it is deserialized.
/// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
/// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow);
/// <summary>
/// Deserializes a <see cref="global::System.Collections.IDictionary" /> into a new instance of <see cref="Commvault.Powershell.Models.DellEmc"
/// />.
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
internal DellEmc(global::System.Collections.IDictionary content)
{
bool returnNow = false;
BeforeDeserializeDictionary(content, ref returnNow);
if (returnNow)
{
return;
}
// actually deserialize
((Commvault.Powershell.Models.IDellEmcInternal)this).Credentials = (Commvault.Powershell.Models.IIdName) content.GetValueForProperty("Credentials",((Commvault.Powershell.Models.IDellEmcInternal)this).Credentials, Commvault.Powershell.Models.IdNameTypeConverter.ConvertFrom);
((Commvault.Powershell.Models.IDellEmcInternal)this).CloudType = (string) content.GetValueForProperty("CloudType",((Commvault.Powershell.Models.IDellEmcInternal)this).CloudType, global::System.Convert.ToString);
((Commvault.Powershell.Models.IDellEmcInternal)this).ServiceHost = (string) content.GetValueForProperty("ServiceHost",((Commvault.Powershell.Models.IDellEmcInternal)this).ServiceHost, global::System.Convert.ToString);
((Commvault.Powershell.Models.IDellEmcInternal)this).Bucket = (string) content.GetValueForProperty("Bucket",((Commvault.Powershell.Models.IDellEmcInternal)this).Bucket, global::System.Convert.ToString);
((Commvault.Powershell.Models.ICloudStorageInternal)this).MediaAgentId = (int?) content.GetValueForProperty("MediaAgentId",((Commvault.Powershell.Models.ICloudStorageInternal)this).MediaAgentId, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int)));
((Commvault.Powershell.Models.ICloudStorageInternal)this).MediaAgentName = (string) content.GetValueForProperty("MediaAgentName",((Commvault.Powershell.Models.ICloudStorageInternal)this).MediaAgentName, global::System.Convert.ToString);
((Commvault.Powershell.Models.ICloudStorageInternal)this).MediaAgent = (Commvault.Powershell.Models.IIdName) content.GetValueForProperty("MediaAgent",((Commvault.Powershell.Models.ICloudStorageInternal)this).MediaAgent, Commvault.Powershell.Models.IdNameTypeConverter.ConvertFrom);
((Commvault.Powershell.Models.ICloudStorageInternal)this).Name = (string) content.GetValueForProperty("Name",((Commvault.Powershell.Models.ICloudStorageInternal)this).Name, global::System.Convert.ToString);
((Commvault.Powershell.Models.IDedupeStorageListInternal)this).UseDeduplication = (bool?) content.GetValueForProperty("UseDeduplication",((Commvault.Powershell.Models.IDedupeStorageListInternal)this).UseDeduplication, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool)));
((Commvault.Powershell.Models.IDedupeStorageListInternal)this).DeduplicationDbLocation = (Commvault.Powershell.Models.IDedupePath[]) content.GetValueForProperty("DeduplicationDbLocation",((Commvault.Powershell.Models.IDedupeStorageListInternal)this).DeduplicationDbLocation, __y => TypeConverterExtensions.SelectToArray<Commvault.Powershell.Models.IDedupePath>(__y, Commvault.Powershell.Models.DedupePathTypeConverter.ConvertFrom));
((Commvault.Powershell.Models.IDellEmcInternal)this).CredentialsId = (int?) content.GetValueForProperty("CredentialsId",((Commvault.Powershell.Models.IDellEmcInternal)this).CredentialsId, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int)));
((Commvault.Powershell.Models.IDellEmcInternal)this).CredentialsName = (string) content.GetValueForProperty("CredentialsName",((Commvault.Powershell.Models.IDellEmcInternal)this).CredentialsName, global::System.Convert.ToString);
AfterDeserializeDictionary(content);
}
/// <summary>
/// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into a new instance of <see cref="Commvault.Powershell.Models.DellEmc"
/// />.
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
internal DellEmc(global::System.Management.Automation.PSObject content)
{
bool returnNow = false;
BeforeDeserializePSObject(content, ref returnNow);
if (returnNow)
{
return;
}
// actually deserialize
((Commvault.Powershell.Models.IDellEmcInternal)this).Credentials = (Commvault.Powershell.Models.IIdName) content.GetValueForProperty("Credentials",((Commvault.Powershell.Models.IDellEmcInternal)this).Credentials, Commvault.Powershell.Models.IdNameTypeConverter.ConvertFrom);
((Commvault.Powershell.Models.IDellEmcInternal)this).CloudType = (string) content.GetValueForProperty("CloudType",((Commvault.Powershell.Models.IDellEmcInternal)this).CloudType, global::System.Convert.ToString);
((Commvault.Powershell.Models.IDellEmcInternal)this).ServiceHost = (string) content.GetValueForProperty("ServiceHost",((Commvault.Powershell.Models.IDellEmcInternal)this).ServiceHost, global::System.Convert.ToString);
((Commvault.Powershell.Models.IDellEmcInternal)this).Bucket = (string) content.GetValueForProperty("Bucket",((Commvault.Powershell.Models.IDellEmcInternal)this).Bucket, global::System.Convert.ToString);
((Commvault.Powershell.Models.ICloudStorageInternal)this).MediaAgentId = (int?) content.GetValueForProperty("MediaAgentId",((Commvault.Powershell.Models.ICloudStorageInternal)this).MediaAgentId, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int)));
((Commvault.Powershell.Models.ICloudStorageInternal)this).MediaAgentName = (string) content.GetValueForProperty("MediaAgentName",((Commvault.Powershell.Models.ICloudStorageInternal)this).MediaAgentName, global::System.Convert.ToString);
((Commvault.Powershell.Models.ICloudStorageInternal)this).MediaAgent = (Commvault.Powershell.Models.IIdName) content.GetValueForProperty("MediaAgent",((Commvault.Powershell.Models.ICloudStorageInternal)this).MediaAgent, Commvault.Powershell.Models.IdNameTypeConverter.ConvertFrom);
((Commvault.Powershell.Models.ICloudStorageInternal)this).Name = (string) content.GetValueForProperty("Name",((Commvault.Powershell.Models.ICloudStorageInternal)this).Name, global::System.Convert.ToString);
((Commvault.Powershell.Models.IDedupeStorageListInternal)this).UseDeduplication = (bool?) content.GetValueForProperty("UseDeduplication",((Commvault.Powershell.Models.IDedupeStorageListInternal)this).UseDeduplication, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool)));
((Commvault.Powershell.Models.IDedupeStorageListInternal)this).DeduplicationDbLocation = (Commvault.Powershell.Models.IDedupePath[]) content.GetValueForProperty("DeduplicationDbLocation",((Commvault.Powershell.Models.IDedupeStorageListInternal)this).DeduplicationDbLocation, __y => TypeConverterExtensions.SelectToArray<Commvault.Powershell.Models.IDedupePath>(__y, Commvault.Powershell.Models.DedupePathTypeConverter.ConvertFrom));
((Commvault.Powershell.Models.IDellEmcInternal)this).CredentialsId = (int?) content.GetValueForProperty("CredentialsId",((Commvault.Powershell.Models.IDellEmcInternal)this).CredentialsId, (__y)=> (int) global::System.Convert.ChangeType(__y, typeof(int)));
((Commvault.Powershell.Models.IDellEmcInternal)this).CredentialsName = (string) content.GetValueForProperty("CredentialsName",((Commvault.Powershell.Models.IDellEmcInternal)this).CredentialsName, global::System.Convert.ToString);
AfterDeserializePSObject(content);
}
/// <summary>
/// Deserializes a <see cref="global::System.Collections.IDictionary" /> into an instance of <see cref="Commvault.Powershell.Models.DellEmc"
/// />.
/// </summary>
/// <param name="content">The global::System.Collections.IDictionary content that should be used.</param>
/// <returns>an instance of <see cref="Commvault.Powershell.Models.IDellEmc" />.</returns>
public static Commvault.Powershell.Models.IDellEmc DeserializeFromDictionary(global::System.Collections.IDictionary content)
{
return new DellEmc(content);
}
/// <summary>
/// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into an instance of <see cref="Commvault.Powershell.Models.DellEmc"
/// />.
/// </summary>
/// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param>
/// <returns>an instance of <see cref="Commvault.Powershell.Models.IDellEmc" />.</returns>
public static Commvault.Powershell.Models.IDellEmc DeserializeFromPSObject(global::System.Management.Automation.PSObject content)
{
return new DellEmc(content);
}
/// <summary>
/// Creates a new instance of <see cref="DellEmc" />, deserializing the content from a json string.
/// </summary>
/// <param name="jsonText">a string containing a JSON serialized instance of this model.</param>
/// <returns>an instance of the <see cref="className" /> model class.</returns>
public static Commvault.Powershell.Models.IDellEmc FromJsonString(string jsonText) => FromJson(Commvault.Powershell.Runtime.Json.JsonNode.Parse(jsonText));
/// <summary>Serializes this instance to a json string.</summary>
/// <returns>a <see cref="System.String" /> containing this model serialized to JSON text.</returns>
public string ToJsonString() => ToJson(null, Commvault.Powershell.Runtime.SerializationMode.IncludeAll)?.ToString();
}
/// Dell EMC ECS (S3-compatible)
[System.ComponentModel.TypeConverter(typeof(DellEmcTypeConverter))]
public partial interface IDellEmc
{
}
} | 87.381579 | 444 | 0.733549 | [
"MIT"
] | Commvault/CVPowershellSDKV2 | generated/api/Models/DellEmc.PowerShell.cs | 13,282 | C# |
using System;
using System.IO;
using System.Reflection;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Excel = NetOffice.ExcelApi;
namespace NetOffice
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("NetOffice Release 1.3 Performance Test - 5000 Cells.");
Console.WriteLine("Write simple text.");
// start excel, and get a new sheet reference
Excel.Application excelApplication = CreateExcelApplication();
Excel.Worksheet sheet = excelApplication.Workbooks.Add().Worksheets.Add() as Excel.Worksheet;
// do test 10 times
List<TimeSpan> timeElapsedList = new List<TimeSpan>();
for (int i = 1; i <= 10; i++)
{
DateTime timeStart = DateTime.Now;
for (int y = 1; y <= 5000; y++)
{
string rangeAdress = "$A" + y.ToString();
sheet.get_Range(rangeAdress).Value = "value";
}
TimeSpan timeElapsed = DateTime.Now - timeStart;
// display info and dispose references
Console.WriteLine("Time Elapsed: {0}", timeElapsed);
timeElapsedList.Add(timeElapsed);
sheet.DisposeChildInstances();
}
// display info & log to file
TimeSpan timeAverage = AppendResultToLogFile(timeElapsedList, "Test1-NetOffice.log");
Console.WriteLine("Time Average: {0}{1}Press any key...", timeAverage, Environment.NewLine);
Console.Read();
// release & quit
excelApplication.Quit();
excelApplication.Dispose();
}
/// <summary>
/// creates a new excel application
/// </summary>
/// <returns></returns>
static Excel.Application CreateExcelApplication()
{
Excel.Application excelApplication = new Excel.ApplicationClass();
excelApplication.DisplayAlerts = false;
excelApplication.Interactive = false;
excelApplication.ScreenUpdating = false;
return excelApplication;
}
/// <summary>
/// writes list items to a logile and append average of items at the end
/// </summary>
/// <param name="timeElapsedList">a list with log results</param>
/// <param name="fileName">name of logfile in current assembly folder </param>
/// <returns>average of timeElapsedList</returns>
static TimeSpan AppendResultToLogFile(List<TimeSpan> timeElapsedList, string fileName)
{
TimeSpan timeSummary = TimeSpan.Zero;
string logFile = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), fileName);
if (File.Exists(logFile))
File.Delete(logFile);
foreach (TimeSpan item in timeElapsedList)
{
timeSummary += item;
string logFileAppend = item.ToString() + Environment.NewLine;
File.AppendAllText(logFile, logFileAppend, Encoding.UTF8);
}
TimeSpan timeAverage = TimeSpan.FromTicks(timeSummary.Ticks / timeElapsedList.Count);
File.AppendAllText(logFile, "Time Average: " + timeAverage.ToString(), Encoding.UTF8);
return timeAverage;
}
}
}
| 38.188889 | 113 | 0.588013 | [
"MIT"
] | igoreksiz/NetOffice | Tests/Performance Tests/Test1/NetOffice/Program.cs | 3,439 | 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.Text;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
internal static partial class Interop
{
internal static partial class Crypt32
{
[StructLayout(LayoutKind.Sequential)]
internal struct CRYPT_ALGORITHM_IDENTIFIER
{
internal IntPtr pszObjId;
internal DATA_BLOB Parameters;
}
}
}
| 25.32 | 71 | 0.71722 | [
"MIT"
] | 333fred/corefx | src/System.Security.Cryptography.Pkcs/src/Interop/Windows/Crypt32/Interop.CRYPT_ALGORITHM_IDENTIFIER.cs | 633 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Globalization;
using System.IO;
namespace Task05BookLibrary
{
class Book
{
public string Title { get; set; }
public string Author { get; set; }
public string Publisher { get; set; }
public DateTime ReleaseDate { get; set; }
public string ISBN { get; set; }
public double Price { get; set; }
public Book(string t, string a, string p, DateTime r, string i, double pr)
{
this.Title = t; this.Author = a; this.Publisher = p; this.ReleaseDate = r; this.ISBN = i; this.Price = pr;
}
}
class Task05BookLibrary
{
static void Main(string[] args)
{
var lines = File.ReadAllLines("input.txt");
File.Delete("output.txt");
var toRepeat = int.Parse(lines[0]);
List<Book> Library = new List<Book>();
for (int i = 1; i < lines.Length; i++)
{
var input = lines[i].Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
var title = input[0];
var author = input[1];
var publisher = input[2];
var releaseDate = DateTime.ParseExact(input[3], "dd.MM.yyyy", CultureInfo.InvariantCulture);
var ISBN = input[4];
var price = double.Parse(input[5]);
var currentBook = new Book(title, author, publisher, releaseDate, ISBN, price);
Library.Add(currentBook);
}
List<string> authors = Library.Select(n => n.Author).Distinct().ToList();
Dictionary<string, double> ouput = new Dictionary<string, double>();
foreach (var author in authors)
{
ouput[author] = Library.Where(n => n.Author == author).Select(n => n.Price).Sum();
}
foreach (var author in ouput.OrderByDescending(n => n.Value).ThenBy(n => n.Key))
{
File.AppendAllText("output.txt",$"{author.Key} -> {author.Value:f2}\r\n");
}
}
}
} | 27 | 118 | 0.543812 | [
"MIT"
] | samuilll/BeginnerExams | PrgrammingFundametnalsFast/09_FilesAndExeptions/Task09BookLibrary/Task09BookLibrary.cs | 2,216 | C# |
/*
* Domain Public API
*
* See https://developer.domain.com.au for more information
*
* The version of the OpenAPI document: v2
* Contact: api@domain.com.au
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using Xunit;
using System;
using System.Linq;
using System.IO;
using System.Collections.Generic;
using Domain.Api.V2.Api;
using Domain.Api.V2.Model;
using Domain.Api.V2.Client;
using System.Reflection;
using Newtonsoft.Json;
namespace Domain.Api.V2.Test.Model
{
/// <summary>
/// Class for testing ListingsV2ListingMedia
/// </summary>
/// <remarks>
/// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech).
/// Please update the test case below to test the model.
/// </remarks>
public class ListingsV2ListingMediaTests : IDisposable
{
// TODO uncomment below to declare an instance variable for ListingsV2ListingMedia
//private ListingsV2ListingMedia instance;
public ListingsV2ListingMediaTests()
{
// TODO uncomment below to create an instance of ListingsV2ListingMedia
//instance = new ListingsV2ListingMedia();
}
public void Dispose()
{
// Cleanup when everything is done.
}
/// <summary>
/// Test an instance of ListingsV2ListingMedia
/// </summary>
[Fact]
public void ListingsV2ListingMediaInstanceTest()
{
// TODO uncomment below to test "IsType" ListingsV2ListingMedia
//Assert.IsType<ListingsV2ListingMedia>(instance);
}
/// <summary>
/// Test the property 'Category'
/// </summary>
[Fact]
public void CategoryTest()
{
// TODO unit test for the property 'Category'
}
/// <summary>
/// Test the property 'Type'
/// </summary>
[Fact]
public void TypeTest()
{
// TODO unit test for the property 'Type'
}
/// <summary>
/// Test the property 'Url'
/// </summary>
[Fact]
public void UrlTest()
{
// TODO unit test for the property 'Url'
}
}
}
| 25.670455 | 99 | 0.595396 | [
"MIT"
] | neildobson-au/InvestOz | src/Integrations/Domain/Domain.Api.V2/src/Domain.Api.V2.Test/Model/ListingsV2ListingMediaTests.cs | 2,259 | C# |
// Copyright 2004-2011 Castle Project - http://www.castleproject.org/
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Castle.Core
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using Castle.Core.Configuration;
/// <summary>
/// Collection of <see cref = "ParameterModel" />
/// </summary>
[Serializable]
[DebuggerDisplay("Count = {dictionary.Count}")]
public class ParameterModelCollection : IEnumerable<ParameterModel>
{
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
private readonly IDictionary<string, ParameterModel> dictionary =
new Dictionary<string, ParameterModel>(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// Gets the count.
/// </summary>
/// <value>The count.</value>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public int Count
{
get { return dictionary.Count; }
}
/// <summary>
/// Gets the <see cref = "ParameterModel" /> with the specified key.
/// </summary>
/// <value></value>
public ParameterModel this[string key]
{
get
{
ParameterModel result;
dictionary.TryGetValue(key, out result);
return result;
}
}
/// <summary>
/// Adds the specified name.
/// </summary>
/// <param name = "name">The name.</param>
/// <param name = "value">The value.</param>
public void Add(string name, string value)
{
Add(name, new ParameterModel(name, value));
}
/// <summary>
/// Adds the specified name.
/// </summary>
/// <param name = "name">The name.</param>
/// <param name = "configNode">The config node.</param>
public void Add(string name, IConfiguration configNode)
{
Add(name, new ParameterModel(name, configNode));
}
/// <summary>
/// Adds the specified key.
/// </summary>
/// <remarks>
/// Not implemented
/// </remarks>
/// <param name = "key">The key.</param>
/// <param name = "value">The value.</param>
private void Add(string key, ParameterModel value)
{
try
{
dictionary.Add(key, value);
}
catch (ArgumentException e)
{
throw new ArgumentException(string.Format("Parameter '{0}' already exists.", key), e);
}
}
/// <summary>
/// Returns an enumerator that can iterate through a collection.
/// </summary>
/// <returns>
/// An <see cref = "T:System.Collections.IEnumerator" />
/// that can be used to iterate through the collection.
/// </returns>
[DebuggerStepThrough]
IEnumerator IEnumerable.GetEnumerator()
{
return dictionary.Values.GetEnumerator();
}
[DebuggerStepThrough]
IEnumerator<ParameterModel> IEnumerable<ParameterModel>.GetEnumerator()
{
return dictionary.Values.GetEnumerator();
}
}
} | 27.491525 | 90 | 0.673243 | [
"Apache-2.0"
] | 111cctv19/Windsor | src/Castle.Windsor/Core/ParameterModelCollection.cs | 3,244 | C# |
using System.Net;
namespace CreativeCoders.Net.Servers.Http.SimpleImpl
{
internal class HttpListenerRequestWrapper : IHttpRequest
{
private readonly HttpListenerRequest _request;
public HttpListenerRequestWrapper(HttpListenerRequest request)
{
_request = request;
Body = new StreamRequestBody(request.InputStream);
}
public IHttpRequestBody Body { get; }
public string ContentType => _request.ContentType;
public string HttpMethod => _request.HttpMethod;
}
} | 26.47619 | 70 | 0.683453 | [
"Apache-2.0"
] | CreativeCodersTeam/Core | source/Net/CreativeCoders.Net/Servers/Http/SimpleImpl/HttpListenerRequestWrapper.cs | 558 | 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 cloudfront-2020-05-31.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.CloudFront.Model
{
/// <summary>
/// Container for the parameters to the CreateDistributionWithTags operation.
/// Create a new distribution with tags.
/// </summary>
public partial class CreateDistributionWithTagsRequest : AmazonCloudFrontRequest
{
private DistributionConfigWithTags _distributionConfigWithTags;
/// <summary>
/// Gets and sets the property DistributionConfigWithTags.
/// <para>
/// The distribution's configuration information.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public DistributionConfigWithTags DistributionConfigWithTags
{
get { return this._distributionConfigWithTags; }
set { this._distributionConfigWithTags = value; }
}
// Check to see if DistributionConfigWithTags property is set
internal bool IsSetDistributionConfigWithTags()
{
return this._distributionConfigWithTags != null;
}
}
} | 32.610169 | 108 | 0.694906 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/CloudFront/Generated/Model/CreateDistributionWithTagsRequest.cs | 1,924 | C# |
namespace Res.Core.TcpTransport
{
public class ErrorEntry
{
public int ErrorCode { get; private set; }
public string Message { get; private set; }
public ErrorEntry(int errorCode, string message)
{
ErrorCode = errorCode;
Message = message;
}
}
} | 23 | 56 | 0.574534 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | heartysoft/res | src/res/Res.Core/TcpTransport/ErrorEntry.cs | 322 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using UnityEngine.AddressableAssets.ResourceLocators;
using UnityEngine.Networking;
using UnityEngine.ResourceManagement;
using UnityEngine.ResourceManagement.AsyncOperations;
using UnityEngine.ResourceManagement.ResourceLocations;
using UnityEngine.ResourceManagement.ResourceProviders;
using UnityEngine.ResourceManagement.Util;
namespace UnityEngine.AddressableAssets.ResourceProviders
{
/// <summary>
/// Provider for content catalogs. This provider makes use of a hash file to determine if a newer version of the catalog needs to be downloaded.
/// </summary>
[DisplayName("Content Catalog Provider")]
public class ContentCatalogProvider : ResourceProviderBase
{
/// <summary>
/// Options for specifying which entry in the catalog dependencies should hold each hash item.
/// The Remote should point to the hash on the server. The Cache should point to the
/// local cache copy of the remote data.
/// </summary>
public enum DependencyHashIndex
{
/// <summary>
/// Use to represent the index of the remote entry in the dependencies list.
/// </summary>
Remote = 0,
/// <summary>
/// Use to represent the index of the cache entry in the dependencies list.
/// </summary>
Cache,
/// <summary>
/// Use to represent the number of entries in the dependencies list.
/// </summary>
Count
}
/// <summary>
/// Use to indicate if the updating the catalog on startup should be disabled.
/// </summary>
public bool DisableCatalogUpdateOnStart = false;
/// <summary>
/// Use to indicate if the local catalog is in a bundle.
/// </summary>
public bool IsLocalCatalogInBundle = false;
internal Dictionary<IResourceLocation, InternalOp> m_LocationToCatalogLoadOpMap = new Dictionary<IResourceLocation, InternalOp>();
ResourceManager m_RM;
/// <summary>
/// Constructor for this provider.
/// </summary>
/// <param name="resourceManagerInstance">The resource manager to use.</param>
public ContentCatalogProvider(ResourceManager resourceManagerInstance)
{
m_RM = resourceManagerInstance;
m_BehaviourFlags = ProviderBehaviourFlags.CanProvideWithFailedDependencies;
}
/// <inheritdoc/>
public override void Release(IResourceLocation location, object obj)
{
if (m_LocationToCatalogLoadOpMap.ContainsKey(location))
{
m_LocationToCatalogLoadOpMap[location].Release();
m_LocationToCatalogLoadOpMap.Remove(location);
}
base.Release(location, obj);
}
internal class InternalOp
{
// int m_StartFrame;
string m_LocalDataPath;
string m_RemoteHashValue;
internal string m_LocalHashValue;
ProvideHandle m_ProviderInterface;
internal ContentCatalogData m_ContentCatalogData;
AsyncOperationHandle<ContentCatalogData> m_ContentCatalogDataLoadOp;
private BundledCatalog m_BundledCatalog;
private bool m_Retried;
private bool m_DisableCatalogUpdateOnStart;
private bool m_IsLocalCatalogInBundle;
public void Start(ProvideHandle providerInterface, bool disableCatalogUpdateOnStart, bool isLocalCatalogInBundle)
{
m_ProviderInterface = providerInterface;
m_DisableCatalogUpdateOnStart = disableCatalogUpdateOnStart;
m_IsLocalCatalogInBundle = isLocalCatalogInBundle;
m_ProviderInterface.SetWaitForCompletionCallback(WaitForCompletionCallback);
m_LocalDataPath = null;
m_RemoteHashValue = null;
List<object> deps = new List<object>(); // TODO: garbage. need to pass actual count and reuse the list
m_ProviderInterface.GetDependencies(deps);
string idToLoad = DetermineIdToLoad(m_ProviderInterface.Location, deps, disableCatalogUpdateOnStart);
Addressables.LogFormat("Addressables - Using content catalog from {0}.", idToLoad);
bool loadCatalogFromLocalBundle = isLocalCatalogInBundle && CanLoadCatalogFromBundle(idToLoad, m_ProviderInterface.Location);
LoadCatalog(idToLoad, loadCatalogFromLocalBundle);
}
bool WaitForCompletionCallback()
{
if (m_ContentCatalogData != null)
return true;
bool ccComplete;
if (m_BundledCatalog != null)
{
ccComplete = m_BundledCatalog.WaitForCompletion();
}
else
{
ccComplete = m_ContentCatalogDataLoadOp.IsDone;
if (!ccComplete)
m_ContentCatalogDataLoadOp.WaitForCompletion();
}
//content catalog op needs the Update to be pumped so we can invoke completion callbacks
if (ccComplete && m_ContentCatalogData == null)
m_ProviderInterface.ResourceManager.Update(Time.unscaledDeltaTime);
return ccComplete;
}
/// <summary>
/// Clear all content catalog data.
/// </summary>
public void Release()
{
m_ContentCatalogData?.CleanData();
}
internal bool CanLoadCatalogFromBundle(string idToLoad, IResourceLocation location)
{
return Path.GetExtension(idToLoad) == ".bundle" &&
idToLoad.Equals(GetTransformedInternalId(location));
}
internal void LoadCatalog(string idToLoad, bool loadCatalogFromLocalBundle)
{
try
{
ProviderLoadRequestOptions providerLoadRequestOptions = null;
if (m_ProviderInterface.Location.Data is ProviderLoadRequestOptions providerData)
providerLoadRequestOptions = providerData.Copy();
if (loadCatalogFromLocalBundle)
{
int webRequestTimeout = providerLoadRequestOptions?.WebRequestTimeout ?? 0;
m_BundledCatalog = new BundledCatalog(idToLoad, webRequestTimeout);
m_BundledCatalog.OnLoaded += ccd =>
{
m_ContentCatalogData = ccd;
OnCatalogLoaded(ccd);
};
m_BundledCatalog.LoadCatalogFromBundleAsync();
}
else
{
ResourceLocationBase location = new ResourceLocationBase(idToLoad, idToLoad,
typeof(JsonAssetProvider).FullName, typeof(ContentCatalogData));
location.Data = providerLoadRequestOptions;
m_ContentCatalogDataLoadOp = m_ProviderInterface.ResourceManager.ProvideResource<ContentCatalogData>(location);
m_ContentCatalogDataLoadOp.Completed += CatalogLoadOpCompleteCallback;
}
}
catch (Exception ex)
{
m_ProviderInterface.Complete<ContentCatalogData>(null, false, ex);
}
}
void CatalogLoadOpCompleteCallback(AsyncOperationHandle<ContentCatalogData> op)
{
m_ContentCatalogData = op.Result;
m_ProviderInterface.ResourceManager.Release(op);
OnCatalogLoaded(m_ContentCatalogData);
}
internal class BundledCatalog
{
private readonly string m_BundlePath;
private bool m_OpInProgress;
private AssetBundleCreateRequest m_LoadBundleRequest;
internal AssetBundle m_CatalogAssetBundle;
private AssetBundleRequest m_LoadTextAssetRequest;
private ContentCatalogData m_CatalogData;
private WebRequestQueueOperation m_WebRequestQueueOperation;
private AsyncOperation m_RequestOperation;
private int m_WebRequestTimeout;
public event Action<ContentCatalogData> OnLoaded;
public bool OpInProgress => m_OpInProgress;
public bool OpIsSuccess => !m_OpInProgress && m_CatalogData != null;
public BundledCatalog(string bundlePath, int webRequestTimeout = 0)
{
if (string.IsNullOrEmpty(bundlePath))
{
throw new ArgumentNullException(nameof(bundlePath), "Catalog bundle path is null.");
}
else if (!bundlePath.EndsWith(".bundle"))
{
throw new ArgumentException("You must supply a valid bundle file path.");
}
m_BundlePath = bundlePath;
m_WebRequestTimeout = webRequestTimeout;
}
~BundledCatalog()
{
Unload();
}
private void Unload()
{
m_CatalogAssetBundle?.Unload(true);
m_CatalogAssetBundle = null;
}
public void LoadCatalogFromBundleAsync()
{
//Debug.Log($"LoadCatalogFromBundleAsync frame : {Time.frameCount}");
if (m_OpInProgress)
{
Addressables.LogError($"Operation in progress : A catalog is already being loaded. Please wait for the operation to complete.");
return;
}
m_OpInProgress = true;
if (ResourceManagerConfig.ShouldPathUseWebRequest(m_BundlePath))
{
var req = UnityWebRequestAssetBundle.GetAssetBundle(m_BundlePath);
if (m_WebRequestTimeout > 0)
req.timeout = m_WebRequestTimeout;
m_WebRequestQueueOperation = WebRequestQueue.QueueRequest(req);
if (m_WebRequestQueueOperation.IsDone)
{
m_RequestOperation = m_WebRequestQueueOperation.Result;
if (m_RequestOperation.isDone)
WebRequestOperationCompleted(m_RequestOperation);
else
m_RequestOperation.completed += WebRequestOperationCompleted;
}
else
{
m_WebRequestQueueOperation.OnComplete += asyncOp =>
{
m_RequestOperation = asyncOp;
m_RequestOperation.completed += WebRequestOperationCompleted;
};
}
}
else
{
m_LoadBundleRequest = AssetBundle.LoadFromFileAsync(m_BundlePath);
m_LoadBundleRequest.completed += loadOp =>
{
if (loadOp is AssetBundleCreateRequest createRequest && createRequest.assetBundle != null)
{
m_CatalogAssetBundle = createRequest.assetBundle;
m_LoadTextAssetRequest = m_CatalogAssetBundle.LoadAllAssetsAsync<TextAsset>();
if (m_LoadTextAssetRequest.isDone)
LoadTextAssetRequestComplete(m_LoadTextAssetRequest);
m_LoadTextAssetRequest.completed += LoadTextAssetRequestComplete;
}
else
{
Addressables.LogError($"Unable to load dependent bundle from location : {m_BundlePath}");
m_OpInProgress = false;
}
};
}
}
private void WebRequestOperationCompleted(AsyncOperation op)
{
UnityWebRequestAsyncOperation remoteReq = op as UnityWebRequestAsyncOperation;
var webReq = remoteReq.webRequest;
DownloadHandlerAssetBundle downloadHandler = webReq.downloadHandler as DownloadHandlerAssetBundle;
if (!UnityWebRequestUtilities.RequestHasErrors(webReq, out UnityWebRequestResult uwrResult))
{
m_CatalogAssetBundle = downloadHandler.assetBundle;
m_LoadTextAssetRequest = m_CatalogAssetBundle.LoadAllAssetsAsync<TextAsset>();
if (m_LoadTextAssetRequest.isDone)
LoadTextAssetRequestComplete(m_LoadTextAssetRequest);
m_LoadTextAssetRequest.completed += LoadTextAssetRequestComplete;
}
else
{
Addressables.LogError($"Unable to load dependent bundle from location : {m_BundlePath}");
m_OpInProgress = false;
}
webReq.Dispose();
}
void LoadTextAssetRequestComplete(AsyncOperation op)
{
if (op is AssetBundleRequest loadRequest
&& loadRequest.asset is TextAsset textAsset
&& textAsset.text != null)
{
m_CatalogData = JsonUtility.FromJson<ContentCatalogData>(textAsset.text);
OnLoaded?.Invoke(m_CatalogData);
}
else
{
Addressables.LogError($"No catalog text assets where found in bundle {m_BundlePath}");
}
Unload();
m_OpInProgress = false;
}
public bool WaitForCompletion()
{
if (m_LoadBundleRequest.assetBundle == null)
return false;
return m_LoadTextAssetRequest.asset != null || m_LoadTextAssetRequest.allAssets != null;
}
}
string GetTransformedInternalId(IResourceLocation loc)
{
if (m_ProviderInterface.ResourceManager == null)
return loc.InternalId;
return m_ProviderInterface.ResourceManager.TransformInternalId(loc);
}
internal string DetermineIdToLoad(IResourceLocation location, IList<object> dependencyObjects, bool disableCatalogUpdateOnStart = false)
{
//default to load actual local source catalog
string idToLoad = GetTransformedInternalId(location);
if (dependencyObjects != null &&
location.Dependencies != null &&
dependencyObjects.Count == (int)DependencyHashIndex.Count &&
location.Dependencies.Count == (int)DependencyHashIndex.Count)
{
var remoteHash = dependencyObjects[(int)DependencyHashIndex.Remote] as string;
m_LocalHashValue = dependencyObjects[(int)DependencyHashIndex.Cache] as string;
Addressables.LogFormat("Addressables - ContentCatalogProvider CachedHash = {0}, RemoteHash = {1}.", m_LocalHashValue, remoteHash);
if (string.IsNullOrEmpty(remoteHash) || disableCatalogUpdateOnStart) //offline
{
if (!string.IsNullOrEmpty(m_LocalHashValue) && !m_Retried) //cache exists and not forcing a retry state
{
idToLoad = GetTransformedInternalId(location.Dependencies[(int)DependencyHashIndex.Cache]).Replace(".hash", ".json");
}
else
{
m_LocalHashValue = Hash128.Compute(idToLoad).ToString();
}
}
else //online
{
if (remoteHash == m_LocalHashValue && !m_Retried) //cache of remote is good and not forcing a retry state
{
idToLoad = GetTransformedInternalId(location.Dependencies[(int)DependencyHashIndex.Cache]).Replace(".hash", ".json");
}
else //remote is different than cache, or no cache
{
idToLoad = GetTransformedInternalId(location.Dependencies[(int)DependencyHashIndex.Remote]).Replace(".hash", ".json");
m_LocalDataPath = GetTransformedInternalId(location.Dependencies[(int)DependencyHashIndex.Cache]).Replace(".hash", ".json");
m_RemoteHashValue = remoteHash;
}
}
}
return idToLoad;
}
private void OnCatalogLoaded(ContentCatalogData ccd)
{
Addressables.LogFormat("Addressables - Content catalog load result = {0}.", ccd);
if (ccd != null)
{
ccd.location = m_ProviderInterface.Location;
ccd.localHash = m_LocalHashValue;
if (!string.IsNullOrEmpty(m_RemoteHashValue) && !string.IsNullOrEmpty(m_LocalDataPath))
{
#if ENABLE_CACHING
var dir = Path.GetDirectoryName(m_LocalDataPath);
if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir))
Directory.CreateDirectory(dir);
var localCachePath = m_LocalDataPath;
Addressables.LogFormat("Addressables - Saving cached content catalog to {0}.", localCachePath);
try
{
File.WriteAllText(localCachePath, JsonUtility.ToJson(ccd));
File.WriteAllText(localCachePath.Replace(".json", ".hash"), m_RemoteHashValue);
}
catch (Exception e)
{
string remoteInternalId = GetTransformedInternalId(m_ProviderInterface.Location.Dependencies[(int)DependencyHashIndex.Remote]);
var errorMessage = $"Unable to load ContentCatalogData from location {remoteInternalId}. Failed to cache catalog to location {localCachePath}.";
ccd = null;
m_ProviderInterface.Complete(ccd, false, new Exception(errorMessage, e));
return;
}
#endif
ccd.localHash = m_RemoteHashValue;
}
m_ProviderInterface.Complete(ccd, true, null);
}
else
{
var errorMessage = $"Unable to load ContentCatalogData from location {m_ProviderInterface.Location}";
if (!m_Retried)
{
m_Retried = true;
//if the prev load path is cache, try to remove cache and reload from remote
var cachePath = GetTransformedInternalId(m_ProviderInterface.Location.Dependencies[(int)DependencyHashIndex.Cache]);
if (m_ContentCatalogDataLoadOp.LocationName == cachePath.Replace(".hash", ".json"))
{
try
{
#if ENABLE_CACHING
File.Delete(cachePath);
#endif
}
catch (Exception)
{
errorMessage += $". Unable to delete cache data from location {cachePath}";
m_ProviderInterface.Complete(ccd, false, new Exception(errorMessage));
return;
}
}
Addressables.LogWarning(errorMessage + ". Attempting to retry...");
Start(m_ProviderInterface, m_DisableCatalogUpdateOnStart, m_IsLocalCatalogInBundle);
}
else
{
m_ProviderInterface.Complete(ccd, false, new Exception(errorMessage + " on second attempt."));
}
}
}
}
///<inheritdoc/>
public override void Provide(ProvideHandle providerInterface)
{
if (!m_LocationToCatalogLoadOpMap.ContainsKey(providerInterface.Location))
m_LocationToCatalogLoadOpMap.Add(providerInterface.Location, new InternalOp());
m_LocationToCatalogLoadOpMap[providerInterface.Location].Start(providerInterface, DisableCatalogUpdateOnStart, IsLocalCatalogInBundle);
}
}
}
| 47.412148 | 172 | 0.537768 | [
"MIT"
] | WeLikeIke/DubitaC | Source/Library/PackageCache/com.unity.addressables@1.19.17/Runtime/ResourceProviders/ContentCatalogProvider.cs | 21,857 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Transactions;
namespace gs
{
public class GenericGCodeParser
{
public GCodeFile Parse(TextReader input)
{
GCodeFile file = new GCodeFile();
int lines = 0;
while ( input.Peek() >= 0 ) {
string line = input.ReadLine();
int nLineNum = lines++;
GCodeLine l = ParseLine(line, nLineNum);
file.AppendLine(l);
}
return file;
}
virtual protected GCodeLine ParseLine(string line, int nLineNum)
{
if (line.Length == 0)
return make_blank(nLineNum);
if (line[0] == ';')
return make_comment(line, nLineNum);
// strip off trailing comment
string comment = null;
int ci = line.IndexOf(';');
if ( ci < 0 ) {
int bo = line.IndexOf('(');
int bc = line.IndexOf(')');
if ( bo >= 0 && bc > 0 )
ci = bo;
}
if ( ci >= 1 ) {
comment = line.Substring(ci);
line = line.Substring(0, ci);
}
string[] tokens = line.Split( (char[])null , StringSplitOptions.RemoveEmptyEntries);
// handle extra spaces at start...?
if (tokens.Length == 0)
return make_blank(nLineNum);
GCodeLine gcode = null;
switch ( tokens[0][0]) {
case ';':
gcode = make_comment(line, nLineNum);
break;
case 'N':
gcode = make_N_code_line(line, tokens, nLineNum);
break;
case 'G':
case 'M':
gcode = make_GM_code_line(line, tokens, nLineNum);
break;
case ':':
gcode = make_control_line(line, tokens, nLineNum);
break;
default:
gcode = make_string_line(line, nLineNum);
break;
}
if ( comment != null )
gcode.comment = comment;
return gcode;
}
// G### and M### code lines
virtual protected GCodeLine make_GM_code_line(string line, string[] tokens, int nLineNum)
{
GCodeLine.LType eType = GCodeLine.LType.UnknownCode;
if (tokens[0][0] == 'G')
eType = GCodeLine.LType.GCode;
else if (tokens[0][0] == 'M')
eType = GCodeLine.LType.MCode;
GCodeLine l = new GCodeLine(nLineNum, eType);
l.orig_string = line;
// [TODO] comments
if (eType == GCodeLine.LType.UnknownCode) {
l.N = int.Parse(tokens[0].Substring(1));
if (tokens.Length > 1)
l.parameters = parse_parameters(tokens, 1);
} else {
var subcodePos = tokens[0].IndexOf('.');
if (subcodePos == -1)
{
l.code = int.Parse(tokens[0].Substring(1));
}
else
{
l.code = int.Parse(tokens[0].Substring(1, subcodePos - 1));
l.subcode = int.Parse(tokens[0].Substring(subcodePos + 1));
}
l.N = l.code;
if (tokens.Length > 1)
l.parameters = parse_parameters(tokens, 1);
}
return l;
}
// N### lines
virtual protected GCodeLine make_N_code_line(string line, string[] tokens, int nLineNum)
{
GCodeLine.LType eType = GCodeLine.LType.UnknownCode;
if (tokens[1][0] == 'G')
eType = GCodeLine.LType.GCode;
else if (tokens[1][0] == 'M')
eType = GCodeLine.LType.MCode;
GCodeLine l = new GCodeLine(nLineNum, eType);
l.orig_string = line;
l.N = int.Parse(tokens[0].Substring(1));
// [TODO] comments
if (eType == GCodeLine.LType.UnknownCode) {
if (tokens.Length > 1)
l.parameters = parse_parameters(tokens, 1);
} else {
l.code = int.Parse(tokens[1].Substring(1));
if (tokens.Length > 2)
l.parameters = parse_parameters(tokens, 2);
}
return l;
}
// any line we can't understand
virtual protected GCodeLine make_string_line(string line, int nLineNum)
{
GCodeLine l = new GCodeLine(nLineNum, GCodeLine.LType.UnknownString);
l.orig_string = line;
return l;
}
// :IF, :ENDIF, :ELSE
virtual protected GCodeLine make_control_line(string line, string[] tokens, int nLineNum)
{
// figure out command type
string command = tokens[0].Substring(1);
GCodeLine.LType eType = GCodeLine.LType.UnknownControl;
if (command.Equals("if", StringComparison.OrdinalIgnoreCase))
eType = GCodeLine.LType.If;
else if (command.Equals("else", StringComparison.OrdinalIgnoreCase))
eType = GCodeLine.LType.Else;
else if (command.Equals("endif", StringComparison.OrdinalIgnoreCase))
eType = GCodeLine.LType.EndIf;
GCodeLine l = new GCodeLine(nLineNum, eType);
l.orig_string = line;
if (tokens.Length > 1)
l.parameters = parse_parameters(tokens, 1);
return l;
}
// line starting with ;
virtual protected GCodeLine make_comment(string line, int nLineNum)
{
GCodeLine l = new GCodeLine(nLineNum, GCodeLine.LType.Comment);
l.orig_string = line;
int iStart = line.IndexOf(';');
l.comment = line.Substring(iStart);
return l;
}
// line with no text at all
virtual protected GCodeLine make_blank(int nLineNum)
{
return new GCodeLine(nLineNum, GCodeLine.LType.Blank);
}
virtual protected GCodeParam[] parse_parameters(string[] tokens, int iStart, int iEnd = -1)
{
if (iEnd == -1)
iEnd = tokens.Length;
int N = iEnd - iStart;
GCodeParam[] paramList = new GCodeParam[N];
for ( int ti = iStart; ti < iEnd; ++ti ) {
int pi = ti - iStart;
bool bHandled = false;
if ( tokens[ti].Contains('=') ) {
parse_equals_parameter(tokens[ti], ref paramList[pi]);
bHandled = true;
} else if ( tokens[ti][0] == 'G' || tokens[ti][0] == 'M' ) {
parse_code_parameter(tokens[ti], ref paramList[pi]);
bHandled = true;
} else if ( is_num_parameter(tokens[ti]) > 0 ) {
parse_noequals_num_parameter( tokens[ti], ref paramList[pi] );
bHandled = true;
} else if ( tokens[ti].Length == 1 ) {
paramList[pi].type = GCodeParam.PType.NoValue;
paramList[pi].identifier = tokens[ti];
bHandled = true;
}
if (!bHandled) {
paramList[pi].type = GCodeParam.PType.TextValue;
paramList[pi].textValue = tokens[ti];
}
}
return paramList;
}
virtual protected bool parse_code_parameter(string token, ref GCodeParam param)
{
param.type = GCodeParam.PType.Code;
param.identifier = token.Substring(0,1);
string value = token.Substring(1);
GCodeUtil.NumberType numType = GCodeUtil.GetNumberType(value);
if (numType == GCodeUtil.NumberType.Integer)
param.intValue = int.Parse(value);
return true;
}
virtual protected int is_num_parameter(string token)
{
int N = token.Length;
bool contains_number = false;
for (int i = 0; i < N && contains_number == false; ++i) {
if (Char.IsDigit(token[i]))
contains_number = true;
}
if (!contains_number)
return -1;
for ( int i = 1; i < N; ++i ) {
string sub = token.Substring(i);
GCodeUtil.NumberType numtype = GCodeUtil.GetNumberType(sub);
if (numtype != GCodeUtil.NumberType.NotANumber) {
return i;
}
}
return -1;
}
virtual protected bool parse_noequals_num_parameter(string token, ref GCodeParam param)
{
int i = is_num_parameter(token);
if ( i >= 0 )
return parse_value_param(token, i, 0, ref param);
return false;
}
virtual protected bool parse_equals_parameter(string token, ref GCodeParam param)
{
int i = token.IndexOf('=');
return parse_value_param(token, i, 1, ref param);
}
virtual protected bool parse_value_param(string token, int split, int skip, ref GCodeParam param)
{
param.identifier = token.Substring(0, split);
string value = token.Substring(split + skip, token.Length - (split+skip));
try {
GCodeUtil.NumberType numType = GCodeUtil.GetNumberType(value);
if (numType == GCodeUtil.NumberType.Decimal) {
param.type = GCodeParam.PType.DoubleValue;
param.doubleValue = double.Parse(value);
return true;
} else if (numType == GCodeUtil.NumberType.Integer) {
param.type = GCodeParam.PType.IntegerValue;
param.intValue = int.Parse(value);
return true;
}
} catch {
// just continue on and do generic string param
}
param.type = GCodeParam.PType.TextValue;
param.textValue = value;
return true;
}
}
}
| 27.284884 | 99 | 0.549329 | [
"MIT"
] | tg73/gsGCode | parsers/GenericGCodeParser.cs | 9,388 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
using TypeSqf.Model;
namespace TypeSqf.Edit.Highlighting
{
public static class SyntaxHighlightingHandler
{
private static string XshdContentSqx
{
get
{
return @"
<?xml version=""1.0""?>
<SyntaxDefinition name=""Sqf"" extensions="".sqf"" xmlns=""http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008"">
<!-- The named colors 'Comment' and 'String' are used in SharpDevelop to detect if a line is inside a multiline string/comment -->
<Color name=""Default"" exampleText=""get; private set;"" />
<Color name=""Comment"" foreground=""#%CommentsForeColor%"" fontWeight=""%CommentsBold%"" fontStyle=""%CommentsItalic%"" exampleText=""// comment"" />
<Color name=""String"" foreground=""#%StringsForeColor%"" fontWeight=""%StringsBold%"" fontStyle=""%StringsItalic%"" exampleText=""string text = "Hello, World!"""/>
<Color name=""PropertyGetSet"" foreground=""#%PropertyGetSetForeColor%"" fontWeight=""%PropertyGetSetBold%"" fontStyle=""%PropertyGetSetItalic%"" exampleText=""get; private set;"" />
<Color name=""ClassItems"" foreground=""#%ClassKeywordForeColor%"" fontWeight=""%ClassKeywordBold%"" fontStyle=""%ClassKeywordItalic%"" exampleText=""namespace Engima"" />
<Color name=""PrivateFields"" foreground=""#%ClassKeywordForeColor%"" fontWeight=""%ClassKeywordBold%"" fontStyle=""%ClassKeywordItalic%"" exampleText=""private []""/>
<Color name=""Brackets"" foreground=""#%BracketsForeColor%"" fontWeight=""%BracketsBold%"" fontStyle=""%BracketsItalic%"" exampleText=""([{}])"" />
<Color name=""NativeTypes"" foreground=""#%TypesForeColor%"" fontWeight=""%TypesBold%"" fontStyle=""%TypesItalic%"" exampleText=""namespace Engima"" />
<Color name=""PrivateVariable"" foreground=""#%PrivateVariableForeColor%"" fontWeight=""%PrivateVariableBold%"" fontStyle=""%PrivateVariableItalic%"" exampleText=""_privateVariable""/>
<Color name=""MemberNames"" foreground=""#%ClassMemberNamesForeColor%"" fontWeight=""%ClassMemberNamesBold%"" fontStyle=""%ClassMemberNamesItalic%"" exampleText=""public property Count""/>
<Color name=""Keywords"" foreground=""#%KeywordsForeColor%"" fontWeight=""%KeywordsBold%"" fontStyle=""%KeywordsItalic%"" exampleText=""if (a) then {} else {}""/>
<Color name=""Operators"" foreground=""#%OperatorsForeColor%"" fontWeight=""%OperatorsBold%"" fontStyle=""%OperatorsItalic%"" exampleText=""== !="" />
<Color name=""GlobalFunctionHeader"" foreground=""#%GlobalFunctionHeaderForeColor%"" fontWeight=""%GlobalFunctionHeaderBold%"" fontStyle=""%GlobalFunctionHeaderItalic%"" exampleText=""o.ToString();""/>
<Color name=""Preprocessor"" foreground=""#%PreprocessorForeColor%"" fontWeight=""%PreprocessorBold%"" fontStyle=""%PreprocessorItalic%"" exampleText=""#region Title"" />
<Color name=""NumberLiterals"" foreground=""#%NumberLiteralsForeColor%"" fontWeight=""%NumberLiteralsBold%"" fontStyle=""%NumberLiteralsItalic%"" exampleText=""3.1415f""/>
<Color name=""ScopeAndBreakCommands"" foreground=""#%ScopeAndBreakCommandsForeColor%"" fontWeight=""%ScopeAndBreakCommandsBold%"" fontStyle=""%ScopeAndBreakCommandsItalic%"" exampleText=""continue; return null;""/>
<Color name=""TryCatchKeywords"" foreground=""#%KeywordsForeColor%"" fontWeight=""%KeywordsBold%"" fontStyle=""%KeywordsItalic%"" exampleText=""try {} catch {} finally {}""/>
<Color name=""ValueLiterals"" foreground=""#%ValueLiteralsForeColor%"" fontWeight=""%ValueLiteralsBold%"" fontStyle=""%ValueLiteralsItalic%"" exampleText=""b = false; a = true;"" />
<Property name=""DocCommentMarker"" value=""///"" />
<RuleSet name=""CommentMarkerSet"">
<Keywords fontWeight=""bold"" foreground=""Red"">
<Word>TODO</Word>
<Word>FIXME</Word>
</Keywords>
<Keywords fontWeight=""bold"" foreground=""#E0E000"">
<Word>HACK</Word>
<Word>UNDONE</Word>
</Keywords>
</RuleSet>
<!-- This is the main ruleset. -->
<RuleSet ignoreCase=""true"">
<!--<Span color=""Preprocessor"">
<Begin>\#</Begin>
<RuleSet name=""PreprocessorSet"">
<Span>
--><!-- preprocessor directives that allows comments --><!--
<Begin fontWeight=""bold"">
(undef|if|elif|else|endif|line)\b
</Begin>
<RuleSet>
<Span color=""Comment"" ruleSet=""CommentMarkerSet"">
<Begin>//</Begin>
</Span>
</RuleSet>
</Span>
<Span>
--><!-- preprocessor directives that don't allow comments --><!--
<Begin fontWeight=""bold"">
(region|endregion|error|warning|pragma)\b
</Begin>
</Span>
</RuleSet>
</Span>-->
<!--<Span color=""Comment"">
<Begin color=""XmlDoc/DocComment"">///</Begin>
<RuleSet>
<Import ruleSet=""XmlDoc/DocCommentSet""/>
<Import ruleSet=""CommentMarkerSet""/>
</RuleSet>
</Span>-->
<Span color=""Comment"" ruleSet=""CommentMarkerSet"">
<Begin>//</Begin>
</Span>
<Span color=""Comment"" ruleSet=""CommentMarkerSet"" multiline=""true"">
<Begin>/\*</Begin>
<End>\*/</End>
</Span>
<Rule color=""Default"">
(?<=\.)
[A-Za-z0-9_]+
</Rule>
<Rule color=""Default"">
(?<=\#region\s+)
[A-Za-z0-9_]+
</Rule>
<Rule color=""NativeTypes"">
(?<=public\s+class\s+)
[A-Za-z0-9_]+
</Rule>
<Rule color=""NativeTypes"">
(?<=namespace\s+)
[A-Za-z0-9_.]+
</Rule>
<Rule color=""Default"">
private\s+(class|constructor|property)
</Rule>
<Rule color=""NativeTypes"">
(?<=public\s+class\s+[A-Za-z0-9_]+\s*:\s*)
[^{]+
</Rule>
<Rule color=""NativeTypes"">
(?<=public\s+class\s+[A-Za-z0-9_]+\s*:\s*)
.+
(?=\{) # followed by ""{""
</Rule>
<Rule color=""NativeTypes"">
(?<=public\s+interface\s+)
[A-Za-z0-9_]+
</Rule>
<Rule color=""NativeTypes"">
(?<=public\s+enum\s+)
[A-Za-z0-9_]+
</Rule>
<Rule color=""NativeTypes"">
(?<=(method|property)\s+)
[A-Za-z0-9._]+
(?=\s+[A-Za-z0-9_]+) # followed by ""{""
</Rule>
<Rule color=""NativeTypes"">
(?<=private\s+)
[A-Za-z0-9._]+
(?=\s+[A-Za-z0-9_]+) # followed by an identifier
</Rule>
<Rule color=""ClassItems"">
private\s+(static\s+)?fields
</Rule>
<Rule color=""ClassItems"">
(?<=\b)
(method|property)
(?=\b) # followed by ""[""
</Rule>
<Rule color=""Keywords"">
(private|params)
(?=\s*\[) # followed by ""[""
</Rule>
<Rule color=""MemberNames"">
(?<=property\s+[A-Za-z0-9._]+\s+)
[A-Za-z0-9._]+
</Rule>
<Rule color=""MemberNames"">
(?<=property\s+)
[A-Za-z0-9._]+
</Rule>
<Rule color=""MemberNames"">
(?<=method\s+[A-Za-z0-9._]+\s+)
[A-Za-z0-9._]+
</Rule>
<Rule color=""MemberNames"">
(?<=method\s+)
[A-Za-z0-9._]+
</Rule>
<Rule color=""MemberNames"">
(?<=(namespace)\s+)
[A-Za-z0-9._]+
</Rule>
<Rule color=""NativeTypes"">
(?<=(\bas|\bnew|\bis)\s+)
[A-Za-z0-9._]+
</Rule>
<Rule color=""PropertyGetSet"">
(get;|set;|private\s+set;|protected\s+set;)
</Rule>
<Rule color=""ClassItems"">
(protected|private|public)\s+(static\s+)?method
</Rule>
<Rule color=""ClassItems"">
(protected|public)\s+((static|virtual|override)\s+)?method
</Rule>
<Rule color=""ClassItems"">
(public|protected)\s+(static\s+)?property
</Rule>
<Rule color=""ClassItems"">
(public)\s+(class|constructor|interface|enum)
</Rule>
<Span color=""String"" multiline=""true"">
<Begin>""</Begin>
<End>""</End>
<RuleSet>
<!-- span for escape sequences -->
<Span begin=""\\"" end="".""/>
</RuleSet>
</Span>
<Keywords color=""ValueLiterals"">
<Word>true</Word>
<Word>false</Word>
<Word>east</Word>
<Word>west</Word>
<Word>blufor</Word>
<Word>opfor</Word>
<Word>civilian</Word>
<Word>resistance</Word>
<Word>independent</Word>
<Word>sideEmpty</Word>
<Word>sideAmbientLife</Word>
<Word>sideLogic</Word>
<Word>objNull</Word>
<Word>controlNull</Word>
<Word>displayNull</Word>
<Word>grpNull</Word>
<Word>locationNull</Word>
<Word>taskNull</Word>
<Word>scriptNull</Word>
<Word>configNull</Word>
<Word>classNull</Word>
<Word>nil</Word>
</Keywords>
<Keywords color=""Keywords"">
<Word>private</Word>
<Word>var</Word>
<Word>new</Word>
<Word>if</Word>
<Word>then</Word>
<Word>exitWith</Word>
<Word>else</Word>
<Word>switch</Word>
<Word>do</Word>
<Word>case</Word>
<Word>default</Word>
<Word>for</Word>
<Word>forEach</Word>
<Word>in</Word>
<Word>while</Word>
<Word>as</Word>
<Word>is</Word>
<Word>return</Word>
</Keywords>
<Keywords color=""ClassItems"">
<Word>using</Word>
<Word>namespace</Word>
<Word>enum</Word>
</Keywords>
<Keywords color=""ScopeAndBreakCommands"">
<Word>scopeName</Word>
<Word>breakTo</Word>
<Word>breakOut</Word>
</Keywords>
<Keywords color=""TryCatchKeywords"">
<Word>try</Word>
<Word>catch</Word>
</Keywords>
<Rule color=""PrivateVariable"">
(?<![\d\w])_[_a-zA-Z0-9]+ # private variable
</Rule>
<Rule color=""Brackets"">
[\{\[\(\)\]\}] # brackets
</Rule>
<Rule color=""Operators"">
(==|!=|<=?|>=?|\!|&&|\|\|) # operators
</Rule>
<!-- Mark previous rule-->
<Rule color=""GlobalFunctionHeader"">
\b
[\d\w_]+ # an identifier
(?=\s*\=\s*\{) # followed by ""= {""
</Rule>
<!-- #define -->
<Rule color=""Preprocessor"">
(\#define|\#ifndef) #starting with ""#define""
(\s+[a-zA-Z][a-zA-Z0-9_]*)? #a macro identifyer
</Rule>
<!-- #else -->
<Rule color=""Preprocessor"">
\#else
</Rule>
<!-- #endif -->
<Rule color=""Preprocessor"">
\#endif
</Rule>
<!-- #include -->
<Rule color=""Preprocessor"">
\#include
</Rule>
<!-- #region -->
<Rule color=""Preprocessor"">
\#region
</Rule>
<!-- #endregion -->
<Rule color=""Preprocessor"">
\#endregion
</Rule>
<Rule color=""Preprocessor"">
\\$
</Rule>
<Rule color=""NumberLiterals"">
0x[0-9A-Fa-f]+
</Rule>
<!-- Digits -->
<Rule color=""NumberLiterals"">
-+ #starting with a minus
[0-9] #integer
|
( \b\d+(\.[0-9]+)? #number with optional floating point
| \.[0-9]+ #or just starting with floating point
)
</Rule>
</RuleSet>
</SyntaxDefinition>
".Trim();
}
}
private static string XshdContentSqf
{
get
{
return @"
<?xml version=""1.0""?>
<SyntaxDefinition name=""Sqf"" extensions="".sqf"" xmlns=""http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008"">
<!-- The named colors 'Comment' and 'String' are used in SharpDevelop to detect if a line is inside a multiline string/comment -->
<Color name=""Comment"" foreground=""#%CommentsForeColor%"" fontWeight=""%CommentsBold%"" fontStyle=""%CommentsItalic%"" exampleText=""// comment"" />
<Color name=""String"" foreground=""#%StringsForeColor%"" fontWeight=""%StringsBold%"" fontStyle=""%StringsItalic%"" exampleText=""string text = "Hello, World!"""/>
<Color name=""Brackets"" foreground=""#%BracketsForeColor%"" fontWeight=""%BracketsBold%"" fontStyle=""%BracketsItalic%"" exampleText=""([{}])"" />
<Color name=""PrivateVariable"" foreground=""#%PrivateVariableForeColor%"" fontWeight=""%PrivateVariableBold%"" fontStyle=""%PrivateVariableItalic%"" exampleText=""_privateVariable""/>
<Color name=""Keywords"" foreground=""#%KeywordsForeColor%"" fontWeight=""%KeywordsBold%"" fontStyle=""%KeywordsItalic%"" exampleText=""if (a) then {} else {}""/>
<Color name=""Operators"" foreground=""#%OperatorsForeColor%"" fontWeight=""%OperatorsBold%"" fontStyle=""%OperatorsItalic%"" exampleText=""== !="" />
<Color name=""GlobalFunctionHeader"" foreground=""#%GlobalFunctionHeaderForeColor%"" fontWeight=""%GlobalFunctionHeaderBold%"" fontStyle=""%GlobalFunctionHeaderItalic%"" exampleText=""o.ToString();""/>
<Color name=""Preprocessor"" foreground=""#%PreprocessorForeColor%"" fontWeight=""%PreprocessorBold%"" fontStyle=""%PreprocessorItalic%"" exampleText=""#region Title"" />
<Color name=""NumberLiterals"" foreground=""#%NumberLiteralsForeColor%"" fontWeight=""%NumberLiteralsBold%"" fontStyle=""%NumberLiteralsItalic%"" exampleText=""3.1415f""/>
<Color name=""ScopeAndBreakCommands"" foreground=""#%ScopeAndBreakCommandsForeColor%"" fontWeight=""%ScopeAndBreakCommandsBold%"" fontStyle=""%ScopeAndBreakCommandsItalic%"" exampleText=""continue; return null;""/>
<Color name=""TryCatchKeywords"" foreground=""#%KeywordsForeColor%"" fontWeight=""%KeywordsBold%"" fontStyle=""%KeywordsItalic%"" exampleText=""try {} catch {} finally {}""/>
<Color name=""ValueLiterals"" foreground=""#%ValueLiteralsForeColor%"" fontWeight=""%ValueLiteralsBold%"" fontStyle=""%ValueLiteralsItalic%"" exampleText=""b = false; a = true;"" />
<Property name=""DocCommentMarker"" value=""///"" />
<RuleSet name=""CommentMarkerSet"">
<Keywords fontWeight=""bold"" foreground=""Red"">
<Word>TODO</Word>
<Word>FIXME</Word>
</Keywords>
<Keywords fontWeight=""bold"" foreground=""#E0E000"">
<Word>HACK</Word>
<Word>UNDONE</Word>
</Keywords>
</RuleSet>
<!-- This is the main ruleset. -->
<RuleSet ignoreCase=""true"">
<!--<Span color=""Preprocessor"">
<Begin>\#</Begin>
<RuleSet name=""PreprocessorSet"">
<Span>
--><!-- preprocessor directives that allows comments --><!--
<Begin fontWeight=""bold"">
(undef|if|elif|else|endif|line)\b
</Begin>
<RuleSet>
<Span color=""Comment"" ruleSet=""CommentMarkerSet"">
<Begin>//</Begin>
</Span>
</RuleSet>
</Span>
<Span>
--><!-- preprocessor directives that don't allow comments --><!--
<Begin fontWeight=""bold"">
(region|endregion|error|warning|pragma)\b
</Begin>
</Span>
</RuleSet>
</Span>-->
<!--<Span color=""Comment"">
<Begin color=""XmlDoc/DocComment"">///</Begin>
<RuleSet>
<Import ruleSet=""XmlDoc/DocCommentSet""/>
<Import ruleSet=""CommentMarkerSet""/>
</RuleSet>
</Span>-->
<Span color=""Comment"" ruleSet=""CommentMarkerSet"">
<Begin>//</Begin>
</Span>
<Span color=""Comment"" ruleSet=""CommentMarkerSet"" multiline=""true"">
<Begin>/\*</Begin>
<End>\*/</End>
</Span>
<Span color=""String"" multiline=""true"">
<Begin>""</Begin>
<End>""</End>
<RuleSet>
<!-- span for escape sequences -->
<Span begin=""\\"" end="".""/>
</RuleSet>
</Span>
<Keywords color=""ValueLiterals"">
<Word>true</Word>
<Word>false</Word>
<Word>east</Word>
<Word>west</Word>
<Word>blufor</Word>
<Word>opfor</Word>
<Word>civilian</Word>
<Word>resistance</Word>
<Word>independent</Word>
<Word>sideEmpty</Word>
<Word>sideAmbientLife</Word>
<Word>sideLogic</Word>
<Word>objNull</Word>
<Word>controlNull</Word>
<Word>displayNull</Word>
<Word>grpNull</Word>
<Word>locationNull</Word>
<Word>taskNull</Word>
<Word>scriptNull</Word>
<Word>configNull</Word>
<Word>classNull</Word>
<Word>nil</Word>
</Keywords>
<Keywords color=""Keywords"">
<Word>params</Word>
<Word>if</Word>
<Word>then</Word>
<Word>exitWith</Word>
<Word>else</Word>
<Word>switch</Word>
<Word>do</Word>
<Word>case</Word>
<Word>default</Word>
<Word>for</Word>
<Word>forEach</Word>
<Word>in</Word>
<Word>while</Word>
<Word>private</Word>
</Keywords>
<Keywords color=""ScopeAndBreakCommands"">
<Word>scopeName</Word>
<Word>breakTo</Word>
<Word>breakOut</Word>
</Keywords>
<Keywords color=""TryCatchKeywords"">
<Word>try</Word>
<Word>catch</Word>
</Keywords>
<Rule color=""PrivateVariable"">
(?<![\d\w])_[_a-zA-Z0-9]+ # private variable
</Rule>
<Rule color=""Brackets"">
[\{\[\(\)\]\}] # brackets
</Rule>
<Rule color=""Operators"">
(==|!=|<=?|>=?|\!|&&|\|\|) # operators
</Rule>
<!-- Mark previous rule-->
<Rule color=""GlobalFunctionHeader"">
\b
[\d\w_]+ # an identifier
(?=\s*\=\s*\{) # followed by ""= {""
</Rule>
<!-- #define -->
<Rule color=""Preprocessor"">
(\#define|\#ifndef) #starting with ""#define""
(\s+[a-zA-Z][a-zA-Z0-9_]*)? #a macro identifyer
</Rule>
<!-- #else -->
<Rule color=""Preprocessor"">
\#else
</Rule>
<!-- #endif -->
<Rule color=""Preprocessor"">
\#endif
</Rule>
<!-- #include -->
<Rule color=""Preprocessor"">
\#include
</Rule>
<!-- #region -->
<Rule color=""Preprocessor"">
\#region
</Rule>
<!-- #endregion -->
<Rule color=""Preprocessor"">
\#endregion
</Rule>
<Rule color=""Preprocessor"">
\\$
</Rule>
<Rule color=""NumberLiterals"">
0x[0-9A-Fa-f]+
</Rule>
<!-- Digits -->
<Rule color=""NumberLiterals"">
-+ #starting with a minus
[0-9] #integer
|
( \b\d+(\.[0-9]+)? #number with optional floating point
| \.[0-9]+ #or just starting with floating point
)
</Rule>
</RuleSet>
</SyntaxDefinition>
".Trim();
}
}
private static string XshdContentSqm
{
get
{
return @"
<?xml version=""1.0""?>
<SyntaxDefinition name=""Sqf"" extensions="".sqf"" xmlns=""http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008"">
<!-- The named colors 'Comment' and 'String' are used in SharpDevelop to detect if a line is inside a multiline string/comment -->
<Color name=""Comment"" foreground=""#%CommentsForeColor%"" fontWeight=""%CommentsBold%"" fontStyle=""%CommentsItalic%"" exampleText=""// comment"" />
<Color name=""String"" foreground=""#%StringsForeColor%"" fontWeight=""%StringsBold%"" fontStyle=""%StringsItalic%"" exampleText=""string text = "Hello, World!"""/>
<Color name=""ClassItems"" foreground=""#%ClassKeywordForeColor%"" fontWeight=""%ClassKeywordBold%"" fontStyle=""%ClassKeywordItalic%"" exampleText=""namespace Engima"" />
<Color name=""Brackets"" foreground=""#%BracketsForeColor%"" fontWeight=""%BracketsBold%"" fontStyle=""%BracketsItalic%"" exampleText=""([{}])"" />
<Color name=""NativeTypes"" foreground=""#%TypesForeColor%"" fontWeight=""%TypesBold%"" fontStyle=""%TypesItalic%"" exampleText=""namespace Engima"" />
<Color name=""Keywords"" foreground=""#%KeywordsForeColor%"" fontWeight=""%KeywordsBold%"" fontStyle=""%KeywordsItalic%"" exampleText=""if (a) then {} else {}""/>
<Color name=""Operators"" foreground=""#%OperatorsForeColor%"" fontWeight=""%OperatorsBold%"" fontStyle=""%OperatorsItalic%"" exampleText=""== !="" />
<Color name=""GlobalFunctionHeader"" foreground=""#%GlobalFunctionHeaderForeColor%"" fontWeight=""%GlobalFunctionHeaderBold%"" fontStyle=""%GlobalFunctionHeaderItalic%"" exampleText=""o.ToString();""/>
<Color name=""Preprocessor"" foreground=""#%PreprocessorForeColor%"" fontWeight=""%PreprocessorBold%"" fontStyle=""%PreprocessorItalic%"" exampleText=""#region Title"" />
<Color name=""NumberLiterals"" foreground=""#%NumberLiteralsForeColor%"" fontWeight=""%NumberLiteralsBold%"" fontStyle=""%NumberLiteralsItalic%"" exampleText=""3.1415f""/>
<Color name=""ValueLiterals"" foreground=""#%ValueLiteralsForeColor%"" fontWeight=""%ValueLiteralsBold%"" fontStyle=""%ValueLiteralsItalic%"" exampleText=""b = false; a = true;"" />
<Property name=""DocCommentMarker"" value=""///"" />
<RuleSet name=""CommentMarkerSet"">
<Keywords fontWeight=""bold"" foreground=""Red"">
<Word>TODO</Word>
<Word>FIXME</Word>
</Keywords>
<Keywords fontWeight=""bold"" foreground=""#E0E000"">
<Word>HACK</Word>
<Word>UNDONE</Word>
</Keywords>
</RuleSet>
<!-- This is the main ruleset. -->
<RuleSet ignoreCase=""true"">
<!--<Span color=""Preprocessor"">
<Begin>\#</Begin>
<RuleSet name=""PreprocessorSet"">
<Span>
--><!-- preprocessor directives that allows comments --><!--
<Begin fontWeight=""bold"">
(undef|if|elif|else|endif|line)\b
</Begin>
<RuleSet>
<Span color=""Comment"" ruleSet=""CommentMarkerSet"">
<Begin>//</Begin>
</Span>
</RuleSet>
</Span>
<Span>
--><!-- preprocessor directives that don't allow comments --><!--
<Begin fontWeight=""bold"">
(region|endregion|error|warning|pragma)\b
</Begin>
</Span>
</RuleSet>
</Span>-->
<!--<Span color=""Comment"">
<Begin color=""XmlDoc/DocComment"">///</Begin>
<RuleSet>
<Import ruleSet=""XmlDoc/DocCommentSet""/>
<Import ruleSet=""CommentMarkerSet""/>
</RuleSet>
</Span>-->
<Span color=""Comment"" ruleSet=""CommentMarkerSet"">
<Begin>//</Begin>
</Span>
<Span color=""Comment"" ruleSet=""CommentMarkerSet"" multiline=""true"">
<Begin>/\*</Begin>
<End>\*/</End>
</Span>
<Rule color=""NativeTypes"">
(?<=class\s+)
[A-Za-z0-9_]+
</Rule>
<Rule color=""NativeTypes"">
(?<=class\s+[A-Za-z0-9_]+\s*:\s*)
[A-Za-z0-9_]+
</Rule>
<Span color=""String"" multiline=""true"">
<Begin>""</Begin>
<End>""</End>
<RuleSet>
<!-- span for escape sequences -->
<Span begin=""\\"" end="".""/>
</RuleSet>
</Span>
<Keywords color=""ValueLiterals"">
<Word>true</Word>
<Word>false</Word>
</Keywords>
<Keywords color=""ClassItems"">
<Word>class</Word>
</Keywords>
<Rule color=""Brackets"">
[\{\[\(\)\]\}] # brackets
</Rule>
<Rule color=""Operators"">
(==|!=|<=?|>=?|\!|&&|\|\|) # operators
</Rule>
<!-- #define -->
<Rule color=""Preprocessor"">
(\#define|\#ifndef) #starting with ""#define""
(\s+[a-zA-Z][a-zA-Z0-9_]*)? #a macro identifyer
</Rule>
<!-- #else -->
<Rule color=""Preprocessor"">
\#else
</Rule>
<!-- #endif -->
<Rule color=""Preprocessor"">
\#endif
</Rule>
<!-- #include -->
<Rule color=""Preprocessor"">
\#include
</Rule>
<!-- #region -->
<Rule color=""Preprocessor"">
\#region
</Rule>
<!-- #endregion -->
<Rule color=""Preprocessor"">
\#endregion
</Rule>
<Rule color=""Preprocessor"">
\\$
</Rule>
<Rule color=""NumberLiterals"">
0x[0-9A-Fa-f]+
</Rule>
<!-- Digits -->
<Rule color=""NumberLiterals"">
-+ #starting with a minus
[0-9] #integer
|
( \b\d+(\.[0-9]+)? #number with optional floating point
| \.[0-9]+ #or just starting with floating point
)
</Rule>
</RuleSet>
</SyntaxDefinition>
".Trim();
}
}
private static string XshdContentExt
{
get
{
return @"
<?xml version=""1.0""?>
<SyntaxDefinition name=""Sqf"" extensions="".sqf"" xmlns=""http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008"">
<!-- The named colors 'Comment' and 'String' are used in SharpDevelop to detect if a line is inside a multiline string/comment -->
<Color name=""Comment"" foreground=""#%CommentsForeColor%"" fontWeight=""%CommentsBold%"" fontStyle=""%CommentsItalic%"" exampleText=""// comment"" />
<Color name=""String"" foreground=""#%StringsForeColor%"" fontWeight=""%StringsBold%"" fontStyle=""%StringsItalic%"" exampleText=""string text = "Hello, World!"""/>
<Color name=""ClassItems"" foreground=""#%ClassKeywordForeColor%"" fontWeight=""%ClassKeywordBold%"" fontStyle=""%ClassKeywordItalic%"" exampleText=""namespace Engima"" />
<Color name=""Brackets"" foreground=""#%BracketsForeColor%"" fontWeight=""%BracketsBold%"" fontStyle=""%BracketsItalic%"" exampleText=""([{}])"" />
<Color name=""NativeTypes"" foreground=""#%TypesForeColor%"" fontWeight=""%TypesBold%"" fontStyle=""%TypesItalic%"" exampleText=""namespace Engima"" />
<Color name=""Keywords"" foreground=""#%KeywordsForeColor%"" fontWeight=""%KeywordsBold%"" fontStyle=""%KeywordsItalic%"" exampleText=""if (a) then {} else {}""/>
<Color name=""Operators"" foreground=""#%OperatorsForeColor%"" fontWeight=""%OperatorsBold%"" fontStyle=""%OperatorsItalic%"" exampleText=""== !="" />
<Color name=""GlobalFunctionHeader"" foreground=""#%GlobalFunctionHeaderForeColor%"" fontWeight=""%GlobalFunctionHeaderBold%"" fontStyle=""%GlobalFunctionHeaderItalic%"" exampleText=""o.ToString();""/>
<Color name=""Preprocessor"" foreground=""#%PreprocessorForeColor%"" fontWeight=""%PreprocessorBold%"" fontStyle=""%PreprocessorItalic%"" exampleText=""#region Title"" />
<Color name=""NumberLiterals"" foreground=""#%NumberLiteralsForeColor%"" fontWeight=""%NumberLiteralsBold%"" fontStyle=""%NumberLiteralsItalic%"" exampleText=""3.1415f""/>
<Color name=""ValueLiterals"" foreground=""#%ValueLiteralsForeColor%"" fontWeight=""%ValueLiteralsBold%"" fontStyle=""%ValueLiteralsItalic%"" exampleText=""b = false; a = true;"" />
<Property name=""DocCommentMarker"" value=""///"" />
<RuleSet name=""CommentMarkerSet"">
<Keywords fontWeight=""bold"" foreground=""Red"">
<Word>TODO</Word>
<Word>FIXME</Word>
</Keywords>
<Keywords fontWeight=""bold"" foreground=""#E0E000"">
<Word>HACK</Word>
<Word>UNDONE</Word>
</Keywords>
</RuleSet>
<!-- This is the main ruleset. -->
<RuleSet ignoreCase=""true"">
<!--<Span color=""Preprocessor"">
<Begin>\#</Begin>
<RuleSet name=""PreprocessorSet"">
<Span>
--><!-- preprocessor directives that allows comments --><!--
<Begin fontWeight=""bold"">
(undef|if|elif|else|endif|line)\b
</Begin>
<RuleSet>
<Span color=""Comment"" ruleSet=""CommentMarkerSet"">
<Begin>//</Begin>
</Span>
</RuleSet>
</Span>
<Span>
--><!-- preprocessor directives that don't allow comments --><!--
<Begin fontWeight=""bold"">
(region|endregion|error|warning|pragma)\b
</Begin>
</Span>
</RuleSet>
</Span>-->
<!--<Span color=""Comment"">
<Begin color=""XmlDoc/DocComment"">///</Begin>
<RuleSet>
<Import ruleSet=""XmlDoc/DocCommentSet""/>
<Import ruleSet=""CommentMarkerSet""/>
</RuleSet>
</Span>-->
<Span color=""Comment"" ruleSet=""CommentMarkerSet"">
<Begin>//</Begin>
</Span>
<Span color=""Comment"" ruleSet=""CommentMarkerSet"" multiline=""true"">
<Begin>/\*</Begin>
<End>\*/</End>
</Span>
<Rule color=""NativeTypes"">
(?<=class\s+)
[A-Za-z0-9_]+
</Rule>
<Rule color=""NativeTypes"">
(?<=class\s+[A-Za-z0-9_]+\s*:\s*)
[A-Za-z0-9_]+
</Rule>
<Span color=""String"">
<Begin>""</Begin>
<End>""</End>
<RuleSet>
<!-- span for escape sequences -->
<Span begin=""\\"" end="".""/>
</RuleSet>
</Span>
<Keywords color=""ValueLiterals"">
<Word>true</Word>
<Word>false</Word>
</Keywords>
<Keywords color=""ClassItems"">
<Word>class</Word>
</Keywords>
<Rule color=""Brackets"">
[\{\[\(\)\]\}] # brackets
</Rule>
<Rule color=""Operators"">
(==|!=|<=?|>=?|\!|&&|\|\|) # operators
</Rule>
<!-- #define -->
<Rule color=""Preprocessor"">
(\#define|\#ifndef) #starting with ""#define""
(\s+[a-zA-Z][a-zA-Z0-9_]*)? #a macro identifyer
</Rule>
<!-- #else -->
<Rule color=""Preprocessor"">
\#else
</Rule>
<!-- #endif -->
<Rule color=""Preprocessor"">
\#endif
</Rule>
<!-- #include -->
<Rule color=""Preprocessor"">
\#include
</Rule>
<!-- #region -->
<Rule color=""Preprocessor"">
\#region
</Rule>
<!-- #endregion -->
<Rule color=""Preprocessor"">
\#endregion
</Rule>
<Rule color=""Preprocessor"">
\\$
</Rule>
<Rule color=""NumberLiterals"">
0x[0-9A-Fa-f]+
</Rule>
<!-- Digits -->
<Rule color=""NumberLiterals"">
-+ #starting with a minus
[0-9] #integer
|
( \b\d+(\.[0-9]+)? #number with optional floating point
| \.[0-9]+ #or just starting with floating point
)
</Rule>
</RuleSet>
</SyntaxDefinition>
".Trim();
}
}
private static string XshdContentCpp
{
get
{
return @"
<?xml version=""1.0""?>
<SyntaxDefinition name=""Sqf"" extensions="".sqf"" xmlns=""http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008"">
<!-- The named colors 'Comment' and 'String' are used in SharpDevelop to detect if a line is inside a multiline string/comment -->
<Color name=""Comment"" foreground=""#%CommentsForeColor%"" fontWeight=""%CommentsBold%"" fontStyle=""%CommentsItalic%"" exampleText=""// comment"" />
<Color name=""String"" foreground=""#%StringsForeColor%"" fontWeight=""%StringsBold%"" fontStyle=""%StringsItalic%"" exampleText=""string text = "Hello, World!"""/>
<Color name=""ClassItems"" foreground=""#%ClassKeywordForeColor%"" fontWeight=""%ClassKeywordBold%"" fontStyle=""%ClassKeywordItalic%"" exampleText=""namespace Engima"" />
<Color name=""Brackets"" foreground=""#%BracketsForeColor%"" fontWeight=""%BracketsBold%"" fontStyle=""%BracketsItalic%"" exampleText=""([{}])"" />
<Color name=""NativeTypes"" foreground=""#%TypesForeColor%"" fontWeight=""%TypesBold%"" fontStyle=""%TypesItalic%"" exampleText=""namespace Engima"" />
<Color name=""Keywords"" foreground=""#%KeywordsForeColor%"" fontWeight=""%KeywordsBold%"" fontStyle=""%KeywordsItalic%"" exampleText=""if (a) then {} else {}""/>
<Color name=""Operators"" foreground=""#%OperatorsForeColor%"" fontWeight=""%OperatorsBold%"" fontStyle=""%OperatorsItalic%"" exampleText=""== !="" />
<Color name=""GlobalFunctionHeader"" foreground=""#%GlobalFunctionHeaderForeColor%"" fontWeight=""%GlobalFunctionHeaderBold%"" fontStyle=""%GlobalFunctionHeaderItalic%"" exampleText=""o.ToString();""/>
<Color name=""Preprocessor"" foreground=""#%PreprocessorForeColor%"" fontWeight=""%PreprocessorBold%"" fontStyle=""%PreprocessorItalic%"" exampleText=""#region Title"" />
<Color name=""NumberLiterals"" foreground=""#%NumberLiteralsForeColor%"" fontWeight=""%NumberLiteralsBold%"" fontStyle=""%NumberLiteralsItalic%"" exampleText=""3.1415f""/>
<Property name=""DocCommentMarker"" value=""///"" />
<RuleSet name=""CommentMarkerSet"">
<Keywords fontWeight=""bold"" foreground=""Red"">
<Word>TODO</Word>
<Word>FIXME</Word>
</Keywords>
<Keywords fontWeight=""bold"" foreground=""#E0E000"">
<Word>HACK</Word>
<Word>UNDONE</Word>
</Keywords>
</RuleSet>
<!-- This is the main ruleset. -->
<RuleSet ignoreCase=""true"">
<!--<Span color=""Preprocessor"">
<Begin>\#</Begin>
<RuleSet name=""PreprocessorSet"">
<Span>
--><!-- preprocessor directives that allows comments --><!--
<Begin fontWeight=""bold"">
(undef|if|elif|else|endif|line)\b
</Begin>
<RuleSet>
<Span color=""Comment"" ruleSet=""CommentMarkerSet"">
<Begin>//</Begin>
</Span>
</RuleSet>
</Span>
<Span>
--><!-- preprocessor directives that don't allow comments --><!--
<Begin fontWeight=""bold"">
(region|endregion|error|warning|pragma)\b
</Begin>
</Span>
</RuleSet>
</Span>-->
<!--<Span color=""Comment"">
<Begin color=""XmlDoc/DocComment"">///</Begin>
<RuleSet>
<Import ruleSet=""XmlDoc/DocCommentSet""/>
<Import ruleSet=""CommentMarkerSet""/>
</RuleSet>
</Span>-->
<Span color=""Comment"" ruleSet=""CommentMarkerSet"">
<Begin>//</Begin>
</Span>
<Span color=""Comment"" ruleSet=""CommentMarkerSet"" multiline=""true"">
<Begin>/\*</Begin>
<End>\*/</End>
</Span>
<Rule color=""NativeTypes"">
(?<=class\s+)
[A-Za-z0-9_]+
</Rule>
<Rule color=""NativeTypes"">
(?<=class\s+[A-Za-z0-9_]+\s*:\s*)
[A-Za-z0-9_]+
</Rule>
<Span color=""String"">
<Begin>""</Begin>
<End>""</End>
<RuleSet>
<!-- span for escape sequences -->
<Span begin=""\\"" end="".""/>
</RuleSet>
</Span>
<Keywords color=""ClassItems"">
<Word>class</Word>
</Keywords>
<Rule color=""Brackets"">
[\{\[\(\)\]\}] # brackets
</Rule>
<Rule color=""Operators"">
(==|!=|<=?|>=?|\!|&&|\|\|) # operators
</Rule>
<!-- #define -->
<Rule color=""Preprocessor"">
(\#define|\#ifndef) #starting with ""#define""
(\s+[a-zA-Z][a-zA-Z0-9_]*)? #a macro identifyer
</Rule>
<!-- #else -->
<Rule color=""Preprocessor"">
\#else
</Rule>
<!-- #endif -->
<Rule color=""Preprocessor"">
\#endif
</Rule>
<!-- #include -->
<Rule color=""Preprocessor"">
\#include
</Rule>
<!-- #region -->
<Rule color=""Preprocessor"">
\#region
</Rule>
<!-- #endregion -->
<Rule color=""Preprocessor"">
\#endregion
</Rule>
<Rule color=""Preprocessor"">
\\$
</Rule>
<Rule color=""NumberLiterals"">
0x[0-9A-Fa-f]+
</Rule>
<!-- Digits -->
<Rule color=""NumberLiterals"">
-+ #starting with a minus
[0-9] #integer
|
( \b\d+(\.[0-9]+)? #number with optional floating point
| \.[0-9]+ #or just starting with floating point
)
</Rule>
</RuleSet>
</SyntaxDefinition>
".Trim();
}
}
private static string XshdContentBasic
{
get
{
return @"
<?xml version=""1.0""?>
<SyntaxDefinition name=""Sqf"" extensions="".sqf"" xmlns=""http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008"">
<!-- The named colors 'Comment' and 'String' are used in SharpDevelop to detect if a line is inside a multiline string/comment -->
<Color name=""Comment"" foreground=""#%CommentsForeColor%"" fontWeight=""%CommentsBold%"" fontStyle=""%CommentsItalic%"" exampleText=""// comment"" />
<Color name=""String"" foreground=""#%StringsForeColor%"" fontWeight=""%StringsBold%"" fontStyle=""%StringsItalic%"" exampleText=""string text = "Hello, World!"""/>
<Color name=""Brackets"" foreground=""#%BracketsForeColor%"" fontWeight=""%BracketsBold%"" fontStyle=""%BracketsItalic%"" exampleText=""([{}])"" />
<Color name=""Keywords"" foreground=""#%KeywordsForeColor%"" fontWeight=""%KeywordsBold%"" fontStyle=""%KeywordsItalic%"" exampleText=""if (a) then {} else {}""/>
<Color name=""Operators"" foreground=""#%OperatorsForeColor%"" fontWeight=""%OperatorsBold%"" fontStyle=""%OperatorsItalic%"" exampleText=""== !="" />
<Color name=""GlobalFunctionHeader"" foreground=""#%GlobalFunctionHeaderForeColor%"" fontWeight=""%GlobalFunctionHeaderBold%"" fontStyle=""%GlobalFunctionHeaderItalic%"" exampleText=""o.ToString();""/>
<Color name=""Preprocessor"" foreground=""#%PreprocessorForeColor%"" fontWeight=""%PreprocessorBold%"" fontStyle=""%PreprocessorItalic%"" exampleText=""#region Title"" />
<Color name=""NumberLiterals"" foreground=""#%NumberLiteralsForeColor%"" fontWeight=""%NumberLiteralsBold%"" fontStyle=""%NumberLiteralsItalic%"" exampleText=""3.1415f""/>
<Color name=""ValueLiterals"" foreground=""#%ValueLiteralsForeColor%"" fontWeight=""%ValueLiteralsBold%"" fontStyle=""%ValueLiteralsItalic%"" exampleText=""b = false; a = true;"" />
<Property name=""DocCommentMarker"" value=""///"" />
<RuleSet name=""CommentMarkerSet"">
<Keywords fontWeight=""bold"" foreground=""Red"">
<Word>TODO</Word>
<Word>FIXME</Word>
</Keywords>
<Keywords fontWeight=""bold"" foreground=""#E0E000"">
<Word>HACK</Word>
<Word>UNDONE</Word>
</Keywords>
</RuleSet>
<!-- This is the main ruleset. -->
<RuleSet ignoreCase=""true"">
<!--<Span color=""Preprocessor"">
<Begin>\#</Begin>
<RuleSet name=""PreprocessorSet"">
<Span>
--><!-- preprocessor directives that allows comments --><!--
<Begin fontWeight=""bold"">
(undef|if|elif|else|endif|line)\b
</Begin>
<RuleSet>
<Span color=""Comment"" ruleSet=""CommentMarkerSet"">
<Begin>//</Begin>
</Span>
</RuleSet>
</Span>
<Span>
--><!-- preprocessor directives that don't allow comments --><!--
<Begin fontWeight=""bold"">
(region|endregion|error|warning|pragma)\b
</Begin>
</Span>
</RuleSet>
</Span>-->
<!--<Span color=""Comment"">
<Begin color=""XmlDoc/DocComment"">///</Begin>
<RuleSet>
<Import ruleSet=""XmlDoc/DocCommentSet""/>
<Import ruleSet=""CommentMarkerSet""/>
</RuleSet>
</Span>-->
<Span color=""Comment"" ruleSet=""CommentMarkerSet"">
<Begin>//</Begin>
</Span>
<Span color=""Comment"" ruleSet=""CommentMarkerSet"" multiline=""true"">
<Begin>/\*</Begin>
<End>\*/</End>
</Span>
<Span color=""String"">
<Begin>""</Begin>
<End>""</End>
<RuleSet>
<!-- span for escape sequences -->
<Span begin=""\\"" end="".""/>
</RuleSet>
</Span>
<Keywords color=""ValueLiterals"">
<Word>true</Word>
<Word>false</Word>
</Keywords>
<Rule color=""Brackets"">
[\{\[\(\)\]\}] # brackets
</Rule>
<Rule color=""Operators"">
(==|!=|<=?|>=?|\!|&&|\|\|) # operators
</Rule>
<!-- #define -->
<Rule color=""Preprocessor"">
(\#define|\#ifndef) #starting with ""#define""
(\s+[a-zA-Z][a-zA-Z0-9_]*)? #a macro identifyer
</Rule>
<!-- #else -->
<Rule color=""Preprocessor"">
\#else
</Rule>
<!-- #endif -->
<Rule color=""Preprocessor"">
\#endif
</Rule>
<!-- #include -->
<Rule color=""Preprocessor"">
\#include
</Rule>
<!-- #region -->
<Rule color=""Preprocessor"">
\#region
</Rule>
<!-- #endregion -->
<Rule color=""Preprocessor"">
\#endregion
</Rule>
<Rule color=""Preprocessor"">
\\$
</Rule>
<Rule color=""NumberLiterals"">
0x[0-9A-Fa-f]+
</Rule>
<!-- Digits -->
<Rule color=""NumberLiterals"">
-+ #starting with a minus
[0-9] #integer
|
( \b\d+(\.[0-9]+)? #number with optional floating point
| \.[0-9]+ #or just starting with floating point
)
</Rule>
</RuleSet>
</SyntaxDefinition>
".Trim();
}
}
private static string GetXshdContent(string extension)
{
if (extension.ToLower() == ".sqx")
{
return XshdContentSqx;
}
else if (extension.ToLower() == ".sqf")
{
return XshdContentSqf;
}
else if (extension.ToLower() == ".ext")
{
return XshdContentExt;
}
else if (extension.ToLower() == ".sqm")
{
return XshdContentSqm;
}
return XshdContentBasic;
}
public static string GetDefinition(string extension, Theme theme = null)
{
if (theme == null && LoadedTheme != null)
{
theme = LoadedTheme;
}
ColorDefinition stringLiterals = theme.GetColorDefinition("StringLiterals");
ColorDefinition comments = theme.GetColorDefinition("Comments");
ColorDefinition classKeywords = theme.GetColorDefinition("ClassKeywords");
ColorDefinition brackets = theme.GetColorDefinition("Brackets");
ColorDefinition types = theme.GetColorDefinition("Types");
ColorDefinition privateVariables = theme.GetColorDefinition("PrivateVariables");
ColorDefinition classMemberNames = theme.GetColorDefinition("ClassMemberNames");
ColorDefinition keywords = theme.GetColorDefinition("Keywords");
ColorDefinition operators = theme.GetColorDefinition("Operators");
ColorDefinition globalFunctions = theme.GetColorDefinition("GlobalFunctions");
ColorDefinition preprocessorKeywords = theme.GetColorDefinition("PreprocessorKeywords");
ColorDefinition numberLiterals = theme.GetColorDefinition("NumberLiterals");
ColorDefinition scopeAndBreakCommands = theme.GetColorDefinition("ScopeAndBreakCommands");
ColorDefinition constantLiterals = theme.GetColorDefinition("ConstantLiterals");
ColorDefinition propertyGetSet = theme.GetColorDefinition("PropertyGetSet");
string xshdContent = GetXshdContent(extension);
return xshdContent
.Replace("%CommentsForeColor%", comments.ForeColor)
.Replace("%CommentsBold%", comments.Bold ? "bold" : "normal")
.Replace("%CommentsItalic%", comments.Italic ? "italic" : "normal")
.Replace("%StringsForeColor%", stringLiterals.ForeColor)
.Replace("%StringsBold%", stringLiterals.Bold ? "bold" : "normal")
.Replace("%StringsItalic%", stringLiterals.Italic ? "italic" : "normal")
.Replace("%ClassKeywordForeColor%", classKeywords.ForeColor)
.Replace("%ClassKeywordBold%", classKeywords.Bold ? "bold" : "normal")
.Replace("%ClassKeywordItalic%", classKeywords.Italic ? "italic" : "normal")
.Replace("%BracketsForeColor%", brackets.ForeColor)
.Replace("%BracketsBold%", brackets.Bold ? "bold" : "normal")
.Replace("%BracketsItalic%", brackets.Italic ? "italic" : "normal")
.Replace("%TypesForeColor%", types.ForeColor)
.Replace("%TypesBold%", types.Bold ? "bold" : "normal")
.Replace("%TypesItalic%", types.Italic ? "italic" : "normal")
.Replace("%PrivateVariableForeColor%", privateVariables.ForeColor)
.Replace("%PrivateVariableBold%", privateVariables.Bold ? "bold" : "normal")
.Replace("%PrivateVariableItalic%", privateVariables.Italic ? "italic" : "normal")
.Replace("%ClassMemberNamesForeColor%", classMemberNames.ForeColor)
.Replace("%ClassMemberNamesBold%", classMemberNames.Bold ? "bold" : "normal")
.Replace("%ClassMemberNamesItalic%", classMemberNames.Italic ? "italic" : "normal")
.Replace("%KeywordsForeColor%", keywords.ForeColor)
.Replace("%KeywordsBold%", keywords.Bold ? "bold" : "normal")
.Replace("%KeywordsItalic%", keywords.Italic ? "italic" : "normal")
.Replace("%OperatorsForeColor%", operators.ForeColor)
.Replace("%OperatorsBold%", operators.Bold ? "bold" : "normal")
.Replace("%OperatorsItalic%", operators.Italic ? "italic" : "normal")
.Replace("%GlobalFunctionHeaderForeColor%", globalFunctions.ForeColor)
.Replace("%GlobalFunctionHeaderBold%", globalFunctions.Bold ? "bold" : "normal")
.Replace("%GlobalFunctionHeaderItalic%", globalFunctions.Italic ? "italic" : "normal")
.Replace("%PreprocessorForeColor%", preprocessorKeywords.ForeColor)
.Replace("%PreprocessorBold%", preprocessorKeywords.Bold ? "bold" : "normal")
.Replace("%PreprocessorItalic%", preprocessorKeywords.Italic ? "italic" : "normal")
.Replace("%NumberLiteralsForeColor%", numberLiterals.ForeColor)
.Replace("%NumberLiteralsBold%", numberLiterals.Bold ? "bold" : "normal")
.Replace("%NumberLiteralsItalic%", numberLiterals.Italic ? "italic" : "normal")
.Replace("%ScopeAndBreakCommandsForeColor%", scopeAndBreakCommands.ForeColor)
.Replace("%ScopeAndBreakCommandsBold%", scopeAndBreakCommands.Bold ? "bold" : "normal")
.Replace("%ScopeAndBreakCommandsItalic%", scopeAndBreakCommands.Italic ? "italic" : "normal")
.Replace("%ValueLiteralsForeColor%", constantLiterals.ForeColor)
.Replace("%ValueLiteralsBold%", constantLiterals.Bold ? "bold" : "normal")
.Replace("%ValueLiteralsItalic%", constantLiterals.Italic ? "italic" : "normal")
.Replace("%PropertyGetSetForeColor%", propertyGetSet.ForeColor)
.Replace("%PropertyGetSetBold%", propertyGetSet.Bold ? "bold" : "normal")
.Replace("%PropertyGetSetItalic%", propertyGetSet.Italic ? "italic" : "normal");
}
public static void WriteThemeToDisc(string filePathName, Theme theme)
{
using (var writer = new StreamWriter(filePathName))
{
var serializer = new XmlSerializer(typeof(Theme));
serializer.Serialize(writer, theme);
writer.Flush();
}
}
public static Theme LoadedTheme { get; private set; }
public static string LoadTheme(string name)
{
try
{
XmlSerializer reader = new XmlSerializer(typeof(Theme));
string fileName = Path.Combine(CurrentApplication.AppDataFolder, "Themes", name + ".xml");
using (StreamReader file = new StreamReader(fileName))
{
LoadedTheme = (Theme)reader.Deserialize(file);
return name;
}
}
catch
{
LoadedTheme = Theme.DefaultLight;
return "Default Light";
}
}
}
}
| 35.210643 | 216 | 0.572019 | [
"MIT"
] | GHSid/Apps-TypeSqfEdit | TypeSqf/Highlighting/SyntaxHighlightingHandler.cs | 47,642 | C# |
#region Copyright (c) 2006-2019 nHydrate.org, All Rights Reserved
// -------------------------------------------------------------------------- *
// NHYDRATE.ORG *
// Copyright (c) 2006-2019 All Rights reserved *
// *
// *
// Permission is hereby granted, free of charge, to any person obtaining a *
// copy of this software and associated documentation files (the "Software"), *
// to deal in the Software without restriction, including without limitation *
// the rights to use, copy, modify, merge, publish, distribute, sublicense, *
// and/or sell copies of the Software, and to permit persons to whom the *
// Software is furnished to do so, subject to the following conditions: *
// *
// The above copyright notice and this permission notice shall be included *
// in all copies or substantial portions of the Software. *
// *
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, *
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES *
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. *
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY *
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, *
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE *
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
// -------------------------------------------------------------------------- *
#endregion
using System.Linq;
using nHydrate.Generator.Common.EventArgs;
using nHydrate.Generator.Common.GeneratorFramework;
using System.Collections.Generic;
using nHydrate.Generator.Models;
namespace nHydrate.Generator.EFDAL.Generators.ComplexTypes
{
[GeneratorItem("ComplexTypesExtenderGenerator", typeof(EFDALProjectGenerator))]
public class ComplexTypesExtenderGenerator : EFDALProjectItemGenerator
{
#region Class Members
private const string RELATIVE_OUTPUT_LOCATION = @"\Entity\";
#endregion
#region Overrides
public override int FileCount
{
get { return GetListSP().Count + GetListFunc().Count; }
}
private List<CustomStoredProcedure> GetListSP()
{
return _model.Database.CustomStoredProcedures
.Where(x => x.Generated && x.GeneratedColumns.Count > 0)
.OrderBy(x => x.Name)
.ToList();
}
private List<Function> GetListFunc()
{
return _model.Database.Functions
.Where(x => x.Generated && x.IsTable)
.OrderBy(x => x.Name)
.ToList();
}
public override void Generate()
{
foreach (var item in GetListSP())
{
var template = new ComplexTypesSPExtenderTemplate(_model, item);
var fullFileName = RELATIVE_OUTPUT_LOCATION + template.FileName;
var eventArgs = new ProjectItemGeneratedEventArgs(fullFileName, template.FileContent, ProjectName, this, false);
OnProjectItemGenerated(this, eventArgs);
}
foreach (var item in GetListFunc())
{
var template = new ComplexTypesFuncExtenderTemplate(_model, item);
var fullFileName = RELATIVE_OUTPUT_LOCATION + template.FileName;
var eventArgs = new ProjectItemGeneratedEventArgs(fullFileName, template.FileContent, ProjectName, this, false);
OnProjectItemGenerated(this, eventArgs);
}
//Process deleted items
foreach (var name in _model.RemovedStoredProcedures)
{
var fullFileName = RELATIVE_OUTPUT_LOCATION + name + ".cs";
var eventArgs = new ProjectItemDeletedEventArgs(fullFileName, ProjectName, this);
OnProjectItemDeleted(this, eventArgs);
}
//Process deleted items
foreach (var name in _model.RemovedFunctions)
{
var fullFileName = RELATIVE_OUTPUT_LOCATION + name + ".cs";
var eventArgs = new ProjectItemDeletedEventArgs(fullFileName, ProjectName, this);
OnProjectItemDeleted(this, eventArgs);
}
var gcEventArgs = new ProjectItemGenerationCompleteEventArgs(this);
OnGenerationComplete(this, gcEventArgs);
}
#endregion
}
} | 46.64486 | 129 | 0.550791 | [
"MIT"
] | mtgibbs/nHydrate | Source/nHydrate.Generator.EFDAL/Generators/ComplexTypes/ComplexTypesExtenderGenerator.cs | 4,991 | C# |
//
// MessageEncodingBindingElement.cs
//
// Author:
// Atsushi Enomoto <atsushi@ximian.com>
//
// Copyright (C) 2005 Novell, Inc. http://www.novell.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.
//
using System;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Security;
using System.Xml;
namespace System.ServiceModel.Channels
{
public abstract class MessageEncodingBindingElement : BindingElement
{
public
MessageEncodingBindingElement ()
{
}
[MonoTODO]
public
MessageEncodingBindingElement (MessageEncodingBindingElement source)
{
MessageVersion = source.MessageVersion;
}
public abstract MessageEncoderFactory
CreateMessageEncoderFactory ();
public abstract MessageVersion MessageVersion { get; set; }
public override T GetProperty<T> (BindingContext ctx)
{
if (typeof (T) == typeof (MessageVersion))
return (T) (object) MessageVersion;
return ctx.GetInnerProperty<T> ();
}
#if !NET_2_1 && !XAMMAC_4_5
[MonoTODO]
protected virtual void OnImportPolicy (XmlElement assertion,
MessageVersion messageVersion,
MetadataImporter exporter,
PolicyConversionContext context)
{
throw new NotImplementedException ();
}
#endif
}
}
| 30.891892 | 73 | 0.757218 | [
"Apache-2.0"
] | AvolitesMarkDaniel/mono | mcs/class/System.ServiceModel/System.ServiceModel.Channels/MessageEncodingBindingElement.cs | 2,286 | C# |
using System;
using System.Collections.Generic;
using System.Reactive.Linq;
using System.Windows;
using System.Windows.Input;
using MahApps.Metro.Controls;
using ReactiveUI;
using ReactiveUI.Fody.Helpers;
using ReactiveUI.Validation.Extensions;
using ReactiveUI.Validation.Helpers;
using ValidationHelper = ReactiveUI.Validation.Helpers.ValidationHelper;
using static TogglDesktop.MessageBox;
namespace TogglDesktop.ViewModels
{
public class PreferencesWindowViewModel : ReactiveValidationObject<PreferencesWindowViewModel>
{
private readonly ShowMessageBoxDelegate _showMessageBox;
private readonly Action _closePreferencesWindow;
private readonly Dictionary<HotKey, string> _knownShortcuts =
new Dictionary<HotKey, string>
{
{ new HotKey(Key.N, ModifierKeys.Control), "New time entry" },
{ new HotKey(Key.O, ModifierKeys.Control), "Continue last entry" },
{ new HotKey(Key.S, ModifierKeys.Control), "Stop time entry" },
{ new HotKey(Key.W, ModifierKeys.Control), "Hide Toggl Track" },
{ new HotKey(Key.R, ModifierKeys.Control), "Sync" },
{ new HotKey(Key.E, ModifierKeys.Control), "Edit time entry" },
{ new HotKey(Key.D, ModifierKeys.Control), "Toggle manual mode" },
{ new HotKey(Key.V, ModifierKeys.Control), "New time entry from clipboard" },
};
private const string ShowHideTogglDescription = "Show/Hide Toggl Track";
private const string ContinueStopTimerDescription = "Continue/Stop Timer";
private HotKey _continueStopTimerSaved;
private HotKey _showHideTogglSaved;
private String _proxyHostSaved;
private readonly ValidationHelper _showHideTogglValidation;
private readonly ValidationHelper _continueStopTimerValidation;
private readonly ValidationHelper _proxyHostValidation;
public PreferencesWindowViewModel(ShowMessageBoxDelegate showMessageBox, Action closePreferencesWindow)
{
_showMessageBox = showMessageBox;
_closePreferencesWindow = closePreferencesWindow;
var isLoggedIn = Observable.FromEvent<Toggl.DisplayLogin, bool>(
onNext => (open, userId) => { onNext(userId != 0); },
x => Toggl.OnLogin += x,
x => Toggl.OnLogin -= x);
ClearCacheCommand = ReactiveCommand.Create(ClearCache, isLoggedIn.ObserveOnDispatcher());
this.WhenAnyValue(x => x.ShowHideToggl)
.Buffer(2, 1)
.Subscribe(b => UpdateKnownShortcuts(b[0], b[1], ShowHideTogglDescription));
this.WhenAnyValue(x => x.ContinueStopTimer)
.Buffer(2, 1)
.Subscribe(b => UpdateKnownShortcuts(b[0], b[1], ContinueStopTimerDescription));
_showHideTogglValidation = this.ValidationRule(
vm => vm.ShowHideToggl,
hotKey => IsHotKeyValid(hotKey, ShowHideTogglDescription),
hotKey => $"This shortcut is already taken by {_knownShortcuts[hotKey]}");
_continueStopTimerValidation = this.ValidationRule(
vm => vm.ContinueStopTimer,
hotKey => IsHotKeyValid(hotKey, ContinueStopTimerDescription),
hotKey => $"This shortcut is already taken by {_knownShortcuts[hotKey]}");
_proxyHostValidation = this.ValidationRule(
x => x.ProxyHost,
proxyHost => Uri.CheckHostName(proxyHost) != UriHostNameType.Unknown,
"Please, enter a valid host");
Toggl.OnDisplayTimelineUI += isEnabled => IsTimelineViewEnabled = isEnabled;
}
public ICommand ClearCacheCommand { get; }
[Reactive]
public HotKey ShowHideToggl { get; set; }
public HotKey GetShowHideTogglIfChanged() =>
!object.Equals(ShowHideToggl, _showHideTogglSaved) ? (ShowHideToggl ?? new HotKey(Key.None)) : null;
[Reactive]
public HotKey ContinueStopTimer { get; set; }
public HotKey GetContinueStopTimerIfChanged() =>
!object.Equals(ContinueStopTimer, _continueStopTimerSaved) ? (ContinueStopTimer ?? new HotKey(Key.None)) : null;
[Reactive]
public string ProxyHost { get; set; }
[Reactive]
public bool IsTimelineViewEnabled { get; private set; }
public void ResetRecordedShortcuts()
{
ShowHideToggl = _showHideTogglSaved;
ContinueStopTimer = _continueStopTimerSaved;
ProxyHost = _proxyHostSaved;
}
public void LoadShortcutsFromSettings()
{
_showHideTogglSaved = LoadHotKey(Toggl.GetKeyShow, Toggl.GetKeyModifierShow);
ShowHideToggl = _showHideTogglSaved;
_continueStopTimerSaved = LoadHotKey(Toggl.GetKeyStart, Toggl.GetKeyModifierStart);
ContinueStopTimer = _continueStopTimerSaved;
}
public void SetSavedProxyHost(String savedProxyHost)
{
_proxyHostSaved = savedProxyHost;
}
public void ResetPropsWithErrorsToPreviousValues()
{
if (!_showHideTogglValidation.IsValid) ShowHideToggl = _showHideTogglSaved;
if (!_continueStopTimerValidation.IsValid) ContinueStopTimer = _continueStopTimerSaved;
if (!_proxyHostValidation.IsValid) ProxyHost = _proxyHostSaved;
}
private bool IsHotKeyValid(HotKey hotKey, string hotKeyDescription)
{
return hotKey.IsNullOrNone() || _knownShortcuts[hotKey] == hotKeyDescription;
}
private void UpdateKnownShortcuts(HotKey previousValue, HotKey newValue, string hotKeyDescription)
{
if (!previousValue.IsNullOrNone() && _knownShortcuts.ContainsKey(previousValue))
{
if (_knownShortcuts[previousValue] == hotKeyDescription)
{
_knownShortcuts.Remove(previousValue);
}
}
if (!newValue.IsNullOrNone())
{
if (!_knownShortcuts.ContainsKey(newValue))
{
_knownShortcuts.Add(newValue, hotKeyDescription);
}
}
}
private static HotKey LoadHotKey(Func<Key> getKey, Func<ModifierKeys> getModifiers)
{
var key = getKey();
return new HotKey(key, key == Key.None ? ModifierKeys.None : getModifiers());
}
private void ClearCache()
{
var result = _showMessageBox(
"This will remove your Toggl user data from this PC and log you out of the Toggl Track app. " +
"Any unsynced data will be lost.\n\nDo you want to continue?", "Clear Cache",
MessageBoxButton.OKCancel, "Clear cache");
if (result == MessageBoxResult.OK)
{
Toggl.ClearCache();
_closePreferencesWindow();
}
}
}
} | 43.909091 | 125 | 0.616701 | [
"BSD-3-Clause"
] | MartinBriza/toggldesktop | src/ui/windows/TogglDesktop/TogglDesktop/ui/ViewModels/PreferencesWindowViewModel.cs | 7,245 | C# |
using FluentNHibernate.Mapping;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace SmartCattle.Web.Domain
{
public class CattlesScoreTbl
{
public virtual int ID { get; set; }
public virtual double BodyCondition { get; set; }
public virtual double Cleanliness { get; set; }
public virtual double Hock { get; set; }
public virtual double Mobility { get; set; }
public virtual double Manure { get; set; }
public virtual double Rumen { get; set; }
public virtual double Teat { get; set; }
public virtual int CattleId { get; set; }
public virtual DateTime Date { get; set; }
public virtual DateTime BodyConditionDate { get; set; }
public virtual DateTime CleanlinessDate { get; set; }
public virtual DateTime HockDate { get; set; }
public virtual DateTime MobilityDate { get; set; }
public virtual DateTime ManureDate { get; set; }
public virtual DateTime RumenDate { get; set; }
public virtual DateTime TeatDate { get; set; }
}
class CattlesScoreTblMapping : ClassMap<CattlesScoreTbl>
{
public CattlesScoreTblMapping()
{
Id(x => x.ID);
Map(x => x.BodyCondition).Nullable();
Map(x => x.Cleanliness).Nullable();
Map(x => x.Hock).Nullable();
Map(x => x.Mobility).Nullable();
Map(x => x.Manure).Nullable();
Map(x => x.Rumen).Nullable();
Map(x => x.Teat).Nullable();
Map(x => x.CattleId).Nullable();
Map(x => x.Date).Nullable();
Map(x => x.BodyConditionDate).Nullable();
Map(x => x.CleanlinessDate).Nullable();
Map(x => x.HockDate).Nullable();
Map(x => x.MobilityDate).Nullable();
Map(x => x.ManureDate).Nullable();
Map(x => x.RumenDate).Nullable();
Map(x => x.TeatDate).Nullable();
Table("SmartCattle.CattlesScoreTbl");
}
}
} | 36.263158 | 63 | 0.578616 | [
"Apache-2.0"
] | PooyaAlamirpour/SmartCattle | SmartCattle.Web/Domain/CattlesScoreTbl.cs | 2,069 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using Snowflake.Services;
namespace Snowflake.Extensibility
{
/// <summary>
/// Represents an always-updated collection of plugins relative to
/// a <see cref="IPluginManager"/> that always gets all the plugins loaded of type T.
/// </summary>
/// <typeparam name="T">The type of plugin</typeparam>
public interface IPluginCollection<T> : IEnumerable<T>
where T : class, IPlugin
{
/// <summary>
/// Gets the instance of T.
/// </summary>
/// <param name="pluginName">The name of the plugin</param>
/// <returns>An instance of the plugin with the given plugin name. </returns>
T? this[string pluginName] { get; }
}
}
| 32.208333 | 89 | 0.639069 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | SnowflakePowered/snowflake | src/Snowflake.Framework.Primitives/Extensibility/IPluginCollection.cs | 775 | C# |
namespace Try_More_On_IEnumerable
{
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using FluentAssertions;
/// <summary>
/// https://dotnetfiddle.net/Widget/vShbOW
/// </summary>
public class T09获取一个链接字符串
{
public static void Run()
{
// 获取一个当前可用的链接字符串
var conn = GetConnectionString().FirstOrDefault();
conn.Should().Be("Source=赛博坦;UID=月x;Password=******");
IEnumerable<string> GetConnectionString()
{
// 从一个文件中获取链接字符串
var connFilename = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "conn.txt");
if (File.Exists(connFilename))
{
var fileContent = File.ReadAllText(connFilename);
yield return fileContent;
}
// 从配置文件中读取链接字符串
var dbConnectionString = ConfigurationManager.ConnectionStrings["db"]?.ConnectionString;
if (!string.IsNullOrEmpty(dbConnectionString))
{
yield return dbConnectionString;
}
// 返回默认的字符串
yield return "Source=赛博坦;UID=月x;Password=******";
}
}
}
} | 31.116279 | 104 | 0.540359 | [
"MIT"
] | newbe36524/Newbe.Demo | src/BlogDemos/Try-More-On-IEnumerable/Try-More-On-IEnumerable/T09获取一个链接字符串.cs | 1,468 | 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.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Build.Collections;
using Microsoft.Build.Evaluation;
using Microsoft.Build.Eventing;
using Microsoft.Build.Execution;
using Microsoft.Build.Framework;
using Microsoft.Build.Shared;
using Microsoft.Build.Shared.FileSystem;
using ElementLocation = Microsoft.Build.Construction.ElementLocation;
using InvalidProjectFileException = Microsoft.Build.Exceptions.InvalidProjectFileException;
using ProjectLoggingContext = Microsoft.Build.BackEnd.Logging.ProjectLoggingContext;
using TargetLoggingContext = Microsoft.Build.BackEnd.Logging.TargetLoggingContext;
using TaskItem = Microsoft.Build.Execution.ProjectItemInstance.TaskItem;
#if MSBUILDENABLEVSPROFILING
using Microsoft.VisualStudio.Profiler;
#endif
#nullable disable
namespace Microsoft.Build.BackEnd
{
/// <summary>
/// Represents which state the target entry is currently in.
/// </summary>
internal enum TargetEntryState
{
/// <summary>
/// The target's dependencies need to be evaluated and pushed onto the target stack.
///
/// Transitions:
/// Execution, ErrorExecution
/// </summary>
Dependencies,
/// <summary>
/// The target is ready to execute its tasks, batched as needed.
///
/// Transitions:
/// ErrorExecution, Completed
/// </summary>
Execution,
/// <summary>
/// The target is ready to provide error tasks.
///
/// Transitions:
/// None
/// </summary>
ErrorExecution,
/// <summary>
/// The target has finished building. All of the results are in the Lookup.
///
/// Transitions:
/// None
/// </summary>
Completed
}
/// <summary>
/// This class represents a single target in the TargetBuilder. It maintains the state machine for a particular target as well as
/// relevant information on outputs generated while a target is running.
/// </summary>
[DebuggerDisplay("Name={_targetSpecification.TargetName} State={_state} Result={_targetResult.ResultCode}")]
internal class TargetEntry : IEquatable<TargetEntry>
{
/// <summary>
/// The BuildRequestEntry to which this target invocation belongs
/// </summary>
private BuildRequestEntry _requestEntry;
/// <summary>
/// The specification of the target being built.
/// </summary>
private TargetSpecification _targetSpecification;
/// <summary>
/// The Target being built. This will be null until the GetTargetInstance() is called, which
/// will cause us to attempt to resolve the actual project instance. At that point
/// if the target doesn't exist, we will throw an InvalidProjectFileException. We do this lazy
/// evaluation because the 'target doesn't exist' message is not supposed to be emitted until
/// the target is actually needed, as opposed to when it is specified, such as in an OnError
/// clause, DependsOnTargets or on the command-line.
/// </summary>
private ProjectTargetInstance _target;
/// <summary>
/// The current state of this entry
/// </summary>
private TargetEntryState _state;
/// <summary>
/// The completion state of the target.
/// </summary>
private TargetResult _targetResult;
/// <summary>
/// The parent entry, which is waiting for us to complete before proceeding.
/// </summary>
private TargetEntry _parentTarget;
/// <summary>
/// Why the parent target built this target.
/// </summary>
private TargetBuiltReason _buildReason;
/// <summary>
/// The expander used to expand item and property markup to evaluated values.
/// </summary>
private Expander<ProjectPropertyInstance, ProjectItemInstance> _expander;
/// <summary>
/// The lookup containing our environment.
/// </summary>
private Lookup _baseLookup;
/// <summary>
/// The build component host.
/// </summary>
private IBuildComponentHost _host;
/// <summary>
/// The target builder callback
/// </summary>
private ITargetBuilderCallback _targetBuilderCallback;
/// <summary>
/// A queue of legacy CallTarget lookup scopes to leave when this target is finished.
/// </summary>
private Stack<Lookup.Scope> _legacyCallTargetScopes;
/// <summary>
/// The cancellation token.
/// </summary>
private CancellationToken _cancellationToken;
/// <summary>
/// Flag indicating whether we are currently executing this target. Used for assertions.
/// </summary>
private bool _isExecuting;
/// <summary>
/// The current task builder.
/// </summary>
private ITaskBuilder _currentTaskBuilder;
/// <summary>
/// The constructor.
/// </summary>
/// <param name="requestEntry">The build request entry for the target.</param>
/// <param name="targetBuilderCallback">The target builder callback.</param>
/// <param name="targetSpecification">The specification for the target to build.</param>
/// <param name="baseLookup">The lookup to use.</param>
/// <param name="parentTarget">The parent of this entry, if any.</param>
/// <param name="buildReason">The reason the parent built this target.</param>
/// <param name="host">The Build Component Host to use.</param>
/// <param name="stopProcessingOnCompletion">True if the target builder should stop processing the current target stack when this target is complete.</param>
internal TargetEntry(BuildRequestEntry requestEntry, ITargetBuilderCallback targetBuilderCallback, TargetSpecification targetSpecification, Lookup baseLookup, TargetEntry parentTarget, TargetBuiltReason buildReason, IBuildComponentHost host, bool stopProcessingOnCompletion)
{
ErrorUtilities.VerifyThrowArgumentNull(requestEntry, nameof(requestEntry));
ErrorUtilities.VerifyThrowArgumentNull(targetBuilderCallback, nameof(targetBuilderCallback));
ErrorUtilities.VerifyThrowArgumentNull(targetSpecification, "targetName");
ErrorUtilities.VerifyThrowArgumentNull(baseLookup, "lookup");
ErrorUtilities.VerifyThrowArgumentNull(host, nameof(host));
_requestEntry = requestEntry;
_targetBuilderCallback = targetBuilderCallback;
_targetSpecification = targetSpecification;
_parentTarget = parentTarget;
_buildReason = buildReason;
_expander = new Expander<ProjectPropertyInstance, ProjectItemInstance>(baseLookup, baseLookup, FileSystems.Default);
_state = TargetEntryState.Dependencies;
_baseLookup = baseLookup;
_host = host;
this.StopProcessingOnCompletion = stopProcessingOnCompletion;
}
/// <summary>
/// Gets or sets a flag indicating if this entry is the result of being listed as an error target in
/// an OnError clause.
/// </summary>
internal bool ErrorTarget
{
get;
set;
}
/// <summary>
/// Sets or sets the location from which this target was referred.
/// </summary>
internal ElementLocation ReferenceLocation
{
get { return _targetSpecification.ReferenceLocation; }
}
/// <summary>
/// Gets or sets a flag indicating that the target builder should stop processing the target
/// stack when this target completes.
/// </summary>
internal bool StopProcessingOnCompletion
{
get;
set;
}
/// <summary>
/// Retrieves the name of the target.
/// </summary>
internal string Name
{
get
{
return _targetSpecification.TargetName;
}
}
/// <summary>
/// Gets the current state of the target
/// </summary>
internal TargetEntryState State
{
get
{
return _state;
}
}
/// <summary>
/// The result of this target.
/// </summary>
internal TargetResult Result
{
get
{
return _targetResult;
}
}
/// <summary>
/// Retrieves the Lookup this target was initialized with, including any modifications which have
/// been made to it while running.
/// </summary>
internal Lookup Lookup
{
get
{
return _baseLookup;
}
}
/// <summary>
/// The target contained by the entry.
/// </summary>
internal ProjectTargetInstance Target
{
get
{
if (_target == null)
{
GetTargetInstance();
}
return _target;
}
}
/// <summary>
/// The build request entry to which this target belongs.
/// </summary>
internal BuildRequestEntry RequestEntry
{
get
{
return _requestEntry;
}
}
/// <summary>
/// The target entry for which we are a dependency.
/// </summary>
internal TargetEntry ParentEntry
{
get
{
return _parentTarget;
}
}
/// <summary>
/// Why the parent target built this target.
/// </summary>
internal TargetBuiltReason BuildReason
{
get
{
return _buildReason;
}
}
#region IEquatable<TargetEntry> Members
/// <summary>
/// Determines equivalence of two target entries. They are considered the same
/// if their names are the same.
/// </summary>
/// <param name="other">The entry to which we compare this one.</param>
/// <returns>True if they are equivalent, false otherwise.</returns>
public bool Equals(TargetEntry other)
{
return String.Equals(this.Name, other.Name, StringComparison.OrdinalIgnoreCase);
}
#endregion
/// <summary>
/// Retrieves the list of dependencies this target needs to have built and moves the target to the next state.
/// Never returns null.
/// </summary>
/// <returns>A collection of targets on which this target depends.</returns>
internal List<TargetSpecification> GetDependencies(ProjectLoggingContext projectLoggingContext)
{
VerifyState(_state, TargetEntryState.Dependencies);
// Resolve the target now, since from this point on we are going to be doing work with the actual instance.
GetTargetInstance();
// We first make sure no batching was attempted with the target's condition.
// UNDONE: (Improvement) We want to allow this actually. In order to do this we need to determine what the
// batching buckets are, and if there are any which aren't empty, return our list of dependencies.
// Only in the case where all bucket conditions fail do we want to skip the target entirely (and
// this skip building the dependencies.)
if (ExpressionShredder.ContainsMetadataExpressionOutsideTransform(_target.Condition))
{
ProjectErrorUtilities.ThrowInvalidProject(_target.ConditionLocation, "TargetConditionHasInvalidMetadataReference", _target.Name, _target.Condition);
}
// If condition is false (based on propertyBag), set this target's state to
// "Skipped" since we won't actually build it.
bool condition = ConditionEvaluator.EvaluateCondition
(
_target.Condition,
ParserOptions.AllowPropertiesAndItemLists,
_expander,
ExpanderOptions.ExpandPropertiesAndItems,
_requestEntry.ProjectRootDirectory,
_target.ConditionLocation,
projectLoggingContext.LoggingService,
projectLoggingContext.BuildEventContext,
FileSystems.Default);
if (!condition)
{
_targetResult = new TargetResult(
Array.Empty<TaskItem>(),
new WorkUnitResult(WorkUnitResultCode.Skipped, WorkUnitActionCode.Continue, null),
projectLoggingContext.BuildEventContext);
_state = TargetEntryState.Completed;
if (!projectLoggingContext.LoggingService.OnlyLogCriticalEvents)
{
// Expand the expression for the Log. Since we know the condition evaluated to false, leave unexpandable properties in the condition so as not to cause an error
string expanded = _expander.ExpandIntoStringAndUnescape(_target.Condition, ExpanderOptions.ExpandPropertiesAndItems | ExpanderOptions.LeavePropertiesUnexpandedOnError | ExpanderOptions.Truncate, _target.ConditionLocation);
// By design: Not building dependencies. This is what NAnt does too.
// NOTE: In the original code, this was logged from the target logging context. However, the target
// hadn't been "started" by then, so you'd get a target message outside the context of a started
// target. In the Task builder (and original Task Engine), a Task Skipped message would be logged in
// the context of the target, not the task. This should be the same, especially given that we
// wish to allow batching on the condition of a target.
var skippedTargetEventArgs = new TargetSkippedEventArgs(message: null)
{
BuildEventContext = projectLoggingContext.BuildEventContext,
TargetName = _target.Name,
TargetFile = _target.Location.File,
ParentTarget = ParentEntry?.Target?.Name,
BuildReason = BuildReason,
SkipReason = TargetSkipReason.ConditionWasFalse,
Condition = _target.Condition,
EvaluatedCondition = expanded
};
projectLoggingContext.LogBuildEvent(skippedTargetEventArgs);
}
return new List<TargetSpecification>();
}
var dependencies = _expander.ExpandIntoStringListLeaveEscaped(_target.DependsOnTargets, ExpanderOptions.ExpandPropertiesAndItems, _target.DependsOnTargetsLocation);
List<TargetSpecification> dependencyTargets = new List<TargetSpecification>();
foreach (string escapedDependency in dependencies)
{
string dependencyTargetName = EscapingUtilities.UnescapeAll(escapedDependency);
dependencyTargets.Add(new TargetSpecification(dependencyTargetName, _target.DependsOnTargetsLocation));
}
_state = TargetEntryState.Execution;
return dependencyTargets;
}
/// <summary>
/// Runs all of the tasks for this target, batched as necessary.
/// </summary>
internal async Task ExecuteTarget(ITaskBuilder taskBuilder, BuildRequestEntry requestEntry, ProjectLoggingContext projectLoggingContext, CancellationToken cancellationToken)
{
try
{
VerifyState(_state, TargetEntryState.Execution);
ErrorUtilities.VerifyThrow(!_isExecuting, "Target {0} is already executing", _target.Name);
_cancellationToken = cancellationToken;
_isExecuting = true;
// Generate the batching buckets. Note that each bucket will get a lookup based on the baseLookup. This lookup will be in its
// own scope, which we will collapse back down into the baseLookup at the bottom of the function.
List<ItemBucket> buckets = BatchingEngine.PrepareBatchingBuckets(GetBatchableParametersForTarget(), _baseLookup, _target.Location);
WorkUnitResult aggregateResult = new WorkUnitResult();
TargetLoggingContext targetLoggingContext = null;
bool targetSuccess = false;
int numberOfBuckets = buckets.Count;
string projectFullPath = requestEntry.RequestConfiguration.ProjectFullPath;
string parentTargetName = null;
if (ParentEntry?.Target != null)
{
parentTargetName = ParentEntry.Target.Name;
}
for (int i = 0; i < numberOfBuckets; i++)
{
ItemBucket bucket = buckets[i];
// If one of the buckets failed, stop building.
if (aggregateResult.ActionCode == WorkUnitActionCode.Stop)
{
break;
}
targetLoggingContext = projectLoggingContext.LogTargetBatchStarted(projectFullPath, _target, parentTargetName, _buildReason);
WorkUnitResult bucketResult = null;
targetSuccess = false;
Lookup.Scope entryForInference = null;
Lookup.Scope entryForExecution = null;
try
{
// This isn't really dependency analysis. This is up-to-date checking. Based on this we will be able to determine if we should
// run tasks in inference or execution mode (or both) or just skip them altogether.
ItemDictionary<ProjectItemInstance> changedTargetInputs;
ItemDictionary<ProjectItemInstance> upToDateTargetInputs;
Lookup lookupForInference;
Lookup lookupForExecution;
// UNDONE: (Refactor) Refactor TargetUpToDateChecker to take a logging context, not a logging service.
MSBuildEventSource.Log.TargetUpToDateStart();
TargetUpToDateChecker dependencyAnalyzer = new TargetUpToDateChecker(requestEntry.RequestConfiguration.Project, _target, targetLoggingContext.LoggingService, targetLoggingContext.BuildEventContext);
DependencyAnalysisResult dependencyResult = dependencyAnalyzer.PerformDependencyAnalysis(bucket, out changedTargetInputs, out upToDateTargetInputs);
MSBuildEventSource.Log.TargetUpToDateStop((int)dependencyResult);
switch (dependencyResult)
{
// UNDONE: Need to enter/leave debugger scope properly for the <Target> element.
case DependencyAnalysisResult.FullBuild:
case DependencyAnalysisResult.IncrementalBuild:
case DependencyAnalysisResult.SkipUpToDate:
// Create the lookups used to hold the current set of properties and items
lookupForInference = bucket.Lookup;
lookupForExecution = bucket.Lookup.Clone();
// Push the lookup stack up one so that we are only modifying items and properties in that scope.
entryForInference = lookupForInference.EnterScope("ExecuteTarget() Inference");
entryForExecution = lookupForExecution.EnterScope("ExecuteTarget() Execution");
// if we're doing an incremental build, we need to effectively run the task twice -- once
// to infer the outputs for up-to-date input items, and once to actually execute the task;
// as a result we need separate sets of item and property collections to track changes
if (dependencyResult == DependencyAnalysisResult.IncrementalBuild)
{
// subset the relevant items to those that are up-to-date
foreach (string itemType in upToDateTargetInputs.ItemTypes)
{
lookupForInference.PopulateWithItems(itemType, upToDateTargetInputs[itemType]);
}
// subset the relevant items to those that have changed
foreach (string itemType in changedTargetInputs.ItemTypes)
{
lookupForExecution.PopulateWithItems(itemType, changedTargetInputs[itemType]);
}
}
// We either have some work to do or at least we need to infer outputs from inputs.
bucketResult = await ProcessBucket(taskBuilder, targetLoggingContext, GetTaskExecutionMode(dependencyResult), lookupForInference, lookupForExecution);
// Now aggregate the result with the existing known results. There are four rules, assuming the target was not
// skipped due to being up-to-date:
// 1. If this bucket failed or was cancelled, the aggregate result is failure.
// 2. If this bucket Succeeded and we have not previously failed, the aggregate result is a success.
// 3. Otherwise, the bucket was skipped, which has no effect on the aggregate result.
// 4. If the bucket's action code says to stop, then we stop, regardless of the success or failure state.
if (dependencyResult != DependencyAnalysisResult.SkipUpToDate)
{
aggregateResult = aggregateResult.AggregateResult(bucketResult);
}
else
{
if (aggregateResult.ResultCode == WorkUnitResultCode.Skipped)
{
aggregateResult = aggregateResult.AggregateResult(new WorkUnitResult(WorkUnitResultCode.Success, WorkUnitActionCode.Continue, null));
}
}
// Pop the lookup scopes, causing them to collapse their values back down into the
// bucket's lookup.
// NOTE: this order is important because when we infer outputs, we are trying
// to produce the same results as would be produced from a full build; as such
// if we're doing both the infer and execute steps, we want the outputs from
// the execute step to override the outputs of the infer step -- this models
// the full build scenario more correctly than if the steps were reversed
entryForInference.LeaveScope();
entryForInference = null;
entryForExecution.LeaveScope();
entryForExecution = null;
targetSuccess = (bucketResult?.ResultCode == WorkUnitResultCode.Success);
break;
case DependencyAnalysisResult.SkipNoInputs:
case DependencyAnalysisResult.SkipNoOutputs:
// We have either no inputs or no outputs, so there is nothing to do.
targetSuccess = true;
break;
}
}
catch (InvalidProjectFileException e)
{
// Make sure the Invalid Project error gets logged *before* TargetFinished. Otherwise,
// the log is confusing.
targetLoggingContext.LogInvalidProjectFileError(e);
entryForInference?.LeaveScope();
entryForExecution?.LeaveScope();
aggregateResult = aggregateResult.AggregateResult(new WorkUnitResult(WorkUnitResultCode.Failed, WorkUnitActionCode.Stop, null));
}
finally
{
// Don't log the last target finished event until we can process the target outputs as we want to attach them to the
// last target batch.
if (targetLoggingContext != null && i < numberOfBuckets - 1)
{
targetLoggingContext.LogTargetBatchFinished(projectFullPath, targetSuccess, null);
targetLoggingContext = null;
}
}
}
// Produce the final results.
List<TaskItem> targetOutputItems = new List<TaskItem>();
try
{
// If any legacy CallTarget operations took place, integrate them back in to the main lookup now.
LeaveLegacyCallTargetScopes();
// Publish the items for each bucket back into the baseLookup. Note that EnterScope() was actually called on each
// bucket inside of the ItemBucket constructor, which is why you don't see it anywhere around here.
foreach (ItemBucket bucket in buckets)
{
bucket.LeaveScope();
}
string targetReturns = _target.Returns;
ElementLocation targetReturnsLocation = _target.ReturnsLocation;
// If there are no targets in the project file that use the "Returns" attribute, that means that we
// revert to the legacy behavior in the case where Returns is not specified (null, rather
// than the empty string, which indicates no returns). Legacy behavior is for all
// of the target's Outputs to be returned.
// On the other hand, if there is at least one target in the file that uses the Returns attribute,
// then all targets in the file are run according to the new behaviour (return nothing unless otherwise
// specified by the Returns attribute).
if (targetReturns == null)
{
if (!_target.ParentProjectSupportsReturnsAttribute)
{
targetReturns = _target.Outputs;
targetReturnsLocation = _target.OutputsLocation;
}
}
if (!String.IsNullOrEmpty(targetReturns))
{
// Determine if we should keep duplicates.
bool keepDupes = ConditionEvaluator.EvaluateCondition
(
_target.KeepDuplicateOutputs,
ParserOptions.AllowPropertiesAndItemLists,
_expander,
ExpanderOptions.ExpandPropertiesAndItems,
requestEntry.ProjectRootDirectory,
_target.KeepDuplicateOutputsLocation,
projectLoggingContext.LoggingService,
projectLoggingContext.BuildEventContext, FileSystems.Default);
// NOTE: we need to gather the outputs in batches, because the output specification may reference item metadata
// Also, we are using the baseLookup, which has possibly had changes made to it since the project started. Because of this, the
// set of outputs calculated here may differ from those which would have been calculated at the beginning of the target. It is
// assumed the user intended this.
List<ItemBucket> batchingBuckets = BatchingEngine.PrepareBatchingBuckets(GetBatchableParametersForTarget(), _baseLookup, _target.Location);
if (keepDupes)
{
foreach (ItemBucket bucket in batchingBuckets)
{
targetOutputItems.AddRange(bucket.Expander.ExpandIntoTaskItemsLeaveEscaped(targetReturns, ExpanderOptions.ExpandAll, targetReturnsLocation));
}
}
else
{
HashSet<TaskItem> addedItems = new HashSet<TaskItem>();
foreach (ItemBucket bucket in batchingBuckets)
{
IList<TaskItem> itemsToAdd = bucket.Expander.ExpandIntoTaskItemsLeaveEscaped(targetReturns, ExpanderOptions.ExpandAll, targetReturnsLocation);
foreach (TaskItem item in itemsToAdd)
{
if (!addedItems.Contains(item))
{
targetOutputItems.Add(item);
addedItems.Add(item);
}
}
}
}
}
}
finally
{
// log the last target finished since we now have the target outputs.
targetLoggingContext?.LogTargetBatchFinished(projectFullPath, targetSuccess, targetOutputItems?.Count > 0 ? targetOutputItems : null);
}
_targetResult = new TargetResult(targetOutputItems.ToArray(), aggregateResult, targetLoggingContext?.BuildEventContext);
if (aggregateResult.ResultCode == WorkUnitResultCode.Failed && aggregateResult.ActionCode == WorkUnitActionCode.Stop)
{
_state = TargetEntryState.ErrorExecution;
}
else
{
_state = TargetEntryState.Completed;
}
}
finally
{
_isExecuting = false;
}
}
/// <summary>
/// Retrieves the error targets for this target.
/// </summary>
/// <param name="projectLoggingContext">The project logging context.</param>
/// <returns>A list of error targets.</returns>
internal List<TargetSpecification> GetErrorTargets(ProjectLoggingContext projectLoggingContext)
{
VerifyState(_state, TargetEntryState.ErrorExecution);
ErrorUtilities.VerifyThrow(_legacyCallTargetScopes == null, "We should have already left any legacy call target scopes.");
List<TargetSpecification> allErrorTargets = new List<TargetSpecification>(_target.OnErrorChildren.Count);
foreach (ProjectOnErrorInstance errorTargetInstance in _target.OnErrorChildren)
{
bool condition = ConditionEvaluator.EvaluateCondition
(
errorTargetInstance.Condition,
ParserOptions.AllowPropertiesAndItemLists,
_expander,
ExpanderOptions.ExpandPropertiesAndItems,
_requestEntry.ProjectRootDirectory,
errorTargetInstance.ConditionLocation,
projectLoggingContext.LoggingService,
projectLoggingContext.BuildEventContext, FileSystems.Default);
if (condition)
{
var errorTargets = _expander.ExpandIntoStringListLeaveEscaped(errorTargetInstance.ExecuteTargets, ExpanderOptions.ExpandPropertiesAndItems, errorTargetInstance.ExecuteTargetsLocation);
foreach (string escapedErrorTarget in errorTargets)
{
string errorTargetName = EscapingUtilities.UnescapeAll(escapedErrorTarget);
allErrorTargets.Add(new TargetSpecification(errorTargetName, errorTargetInstance.ExecuteTargetsLocation));
}
}
}
// If this target never executed (for instance, because one of its dependencies errored) then we need to
// create a result for this target to report when it gets to the Completed state.
if (_targetResult == null)
{
_targetResult = new TargetResult(Array.Empty<TaskItem>(), new WorkUnitResult(WorkUnitResultCode.Failed, WorkUnitActionCode.Stop, null));
}
_state = TargetEntryState.Completed;
return allErrorTargets;
}
/// <summary>
/// Gathers the results from the target into the base lookup of the target.
/// </summary>
/// <returns>The base lookup for this target.</returns>
internal TargetResult GatherResults()
{
VerifyState(_state, TargetEntryState.Completed);
ErrorUtilities.VerifyThrow(_legacyCallTargetScopes == null, "We should have already left any legacy call target scopes.");
// By now all of the bucket lookups have been collapsed into this lookup, which we can return.
return _targetResult;
}
/// <summary>
/// Enters a legacy calltarget scope.
/// </summary>
/// <param name="lookup">The lookup to enter with.</param>
internal void EnterLegacyCallTargetScope(Lookup lookup)
{
if (_legacyCallTargetScopes == null)
{
_legacyCallTargetScopes = new Stack<Lookup.Scope>();
}
_legacyCallTargetScopes.Push(lookup.EnterScope("EnterLegacyCallTargetScope()"));
}
/// <summary>
/// This method is used by the Target Builder to indicate that the target should run in error mode rather than normal mode.
/// </summary>
internal void MarkForError()
{
ErrorUtilities.VerifyThrow(_state != TargetEntryState.Completed, "State must not be Completed. State is {0}.", _state);
_state = TargetEntryState.ErrorExecution;
}
/// <summary>
/// This method is used by the Target Builder to indicate that a child of this target has failed and that work should not
/// continue in Completed / Skipped mode. We do not want to mark the state to run in ErrorExecution mode so that the
/// OnError targets do not run (the target was skipped due to condition so OnError targets should not run).
/// </summary>
internal void MarkForStop()
{
ErrorUtilities.VerifyThrow(_state == TargetEntryState.Completed, "State must be Completed. State is {0}.", _state);
ErrorUtilities.VerifyThrow(_targetResult.ResultCode == TargetResultCode.Skipped, "ResultCode must be Skipped. ResultCode is {0}.", _state);
ErrorUtilities.VerifyThrow(_targetResult.WorkUnitResult.ActionCode == WorkUnitActionCode.Continue, "ActionCode must be Continue. ActionCode is {0}.", _state);
_targetResult.WorkUnitResult.ActionCode = WorkUnitActionCode.Stop;
}
/// <summary>
/// Leaves all the call target scopes in the order they were entered.
/// </summary>
internal void LeaveLegacyCallTargetScopes()
{
if (_legacyCallTargetScopes != null)
{
while (_legacyCallTargetScopes.Count != 0)
{
Lookup.Scope entry = _legacyCallTargetScopes.Pop();
entry.LeaveScope();
}
_legacyCallTargetScopes = null;
}
}
/// <summary>
/// Walks through the set of tasks for this target and processes them by handing them off to the TaskBuilder.
/// </summary>
/// <returns>
/// The result of the tasks, based on the last task which ran.
/// </returns>
private async Task<WorkUnitResult> ProcessBucket(ITaskBuilder taskBuilder, TargetLoggingContext targetLoggingContext, TaskExecutionMode mode, Lookup lookupForInference, Lookup lookupForExecution)
{
WorkUnitResultCode aggregatedTaskResult = WorkUnitResultCode.Success;
WorkUnitActionCode finalActionCode = WorkUnitActionCode.Continue;
WorkUnitResult lastResult = new WorkUnitResult(WorkUnitResultCode.Success, WorkUnitActionCode.Continue, null);
try
{
// Grab the task builder so if cancel is called it will have something to operate on.
_currentTaskBuilder = taskBuilder;
int currentTask = 0;
// Walk through all of the tasks and execute them in order.
for (; (currentTask < _target.Children.Count) && !_cancellationToken.IsCancellationRequested; ++currentTask)
{
ProjectTargetInstanceChild targetChildInstance = _target.Children[currentTask];
// Execute the task.
lastResult = await taskBuilder.ExecuteTask(targetLoggingContext, _requestEntry, _targetBuilderCallback, targetChildInstance, mode, lookupForInference, lookupForExecution, _cancellationToken);
if (lastResult.ResultCode == WorkUnitResultCode.Failed)
{
aggregatedTaskResult = WorkUnitResultCode.Failed;
}
else if (lastResult.ResultCode == WorkUnitResultCode.Success && aggregatedTaskResult != WorkUnitResultCode.Failed)
{
aggregatedTaskResult = WorkUnitResultCode.Success;
}
if (lastResult.ActionCode == WorkUnitActionCode.Stop)
{
finalActionCode = WorkUnitActionCode.Stop;
break;
}
}
if (_cancellationToken.IsCancellationRequested)
{
aggregatedTaskResult = WorkUnitResultCode.Canceled;
finalActionCode = WorkUnitActionCode.Stop;
}
}
finally
{
_currentTaskBuilder = null;
}
return new WorkUnitResult(aggregatedTaskResult, finalActionCode, lastResult.Exception);
}
/// <summary>
/// Gets the task execution mode based
/// </summary>
/// <param name="analysis">The result of the up-to-date check.</param>
/// <returns>The mode to be used to execute tasks.</returns>
private TaskExecutionMode GetTaskExecutionMode(DependencyAnalysisResult analysis)
{
TaskExecutionMode executionMode;
if ((analysis == DependencyAnalysisResult.SkipUpToDate) ||
(analysis == DependencyAnalysisResult.IncrementalBuild))
{
executionMode = TaskExecutionMode.InferOutputsOnly;
}
else
{
executionMode = TaskExecutionMode.ExecuteTaskAndGatherOutputs;
}
// Execute the task using the items that need to be (re)built
if ((analysis == DependencyAnalysisResult.FullBuild) ||
(analysis == DependencyAnalysisResult.IncrementalBuild))
{
executionMode |= TaskExecutionMode.ExecuteTaskAndGatherOutputs;
}
return executionMode;
}
/// <summary>
/// Verifies that the target's state is as expected.
/// </summary>
/// <param name="actual">The actual value</param>
/// <param name="expected">The expected value</param>
private void VerifyState(TargetEntryState actual, TargetEntryState expected)
{
ErrorUtilities.VerifyThrow(actual == expected, "Expected state {1}. Got {0}", actual, expected);
}
/// <summary>
/// Gets the list of parameters which are batchable for a target
/// PERF: (Refactor) This used to be a method on the target, and it would
/// cache its values so this would only be computed once for each
/// target. We should consider doing something similar for perf reasons.
/// </summary>
/// <returns>A list of batchable parameters</returns>
private List<string> GetBatchableParametersForTarget()
{
List<string> batchableTargetParameters = new List<string>();
if (_target.Inputs.Length > 0)
{
batchableTargetParameters.Add(_target.Inputs);
}
if (_target.Outputs.Length > 0)
{
batchableTargetParameters.Add(_target.Outputs);
}
if (!string.IsNullOrEmpty(_target.Returns))
{
batchableTargetParameters.Add(_target.Returns);
}
return batchableTargetParameters;
}
/// <summary>
/// Resolves the target. If it doesn't exist in the project, throws an InvalidProjectFileException.
/// </summary>
private void GetTargetInstance()
{
_requestEntry.RequestConfiguration.Project.Targets.TryGetValue(_targetSpecification.TargetName, out _target);
ProjectErrorUtilities.VerifyThrowInvalidProject
(
_target != null,
_targetSpecification.ReferenceLocation ?? _requestEntry.RequestConfiguration.Project.ProjectFileLocation,
"TargetDoesNotExist",
_targetSpecification.TargetName
);
}
}
}
| 47.026002 | 282 | 0.575694 | [
"MIT"
] | AlexanderSemenyak/msbuild | src/Build/BackEnd/Components/RequestBuilder/TargetEntry.cs | 43,405 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace LeetCode_11
{
public class Solution
{
public int MaxArea(int[] height)
{
var maxArea = 0;
for(var i = 0; i < height.Length; i++)
{
for(var j = i + 1; j < height.Length; j++)
{
var iHeight = height[i] < height[j] ? height[i] : height[j];
var iWidth = j - i;
var iArea = iHeight * iWidth;
maxArea = iArea > maxArea ? iArea : maxArea;
}
}
return maxArea;
}
}
}
| 23.678571 | 80 | 0.435897 | [
"MIT"
] | sdlfly2000/LeetCode | LeetCode/LeetCode-11/Solution.cs | 665 | C# |
using UnityEngine;
public class SetUI : MonoBehaviour
{
private void Start()
{
if (SetAspectRatio.setAspectRatio.RightAspectRatio == false)
{
try { GameObject.Find("Tap To Retry text").GetComponent<RectTransform>().localPosition = new Vector3(-30, -500); } catch { }
}
else
{
enabled = false;
}
}
}
| 21.444444 | 136 | 0.562176 | [
"MIT"
] | SolomonRosemite/Unity-FutureCube | FutureCube/Assets/Scripts/SetUI.cs | 388 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ModelAllPublicSetReadOnlyListOfNullableParent.cs" company="OBeautifulCode">
// Copyright (c) OBeautifulCode 2018. All rights reserved.
// </copyright>
// <auto-generated>
// Sourced from OBeautifulCode.CodeGen.ModelObject.Test.CodeGeneratorTest
// </auto-generated>
// --------------------------------------------------------------------------------------------------------------------
namespace OBeautifulCode.CodeGen.ModelObject.Test
{
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using FakeItEasy;
using OBeautifulCode.Assertion.Recipes;
using OBeautifulCode.CodeAnalysis.Recipes;
using OBeautifulCode.Equality.Recipes;
using OBeautifulCode.Type;
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix", Justification = ObcSuppressBecause.CA1711_IdentifiersShouldNotHaveIncorrectSuffix_TypeNameAddedAsSuffixForTestsWhereTypeIsPrimaryConcern)]
public abstract partial class ModelAllPublicSetReadOnlyListOfNullableParent : IModelViaCodeGen
{
[SuppressMessage("Microsoft.Design", "CA1002: DoNotExposeGenericLists")]
[SuppressMessage("Microsoft.Naming", "CA1720: IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public IReadOnlyList<bool?> ParentReadOnlyListInterfaceOfNullableBoolProperty { get; set; }
[SuppressMessage("Microsoft.Design", "CA1002: DoNotExposeGenericLists")]
[SuppressMessage("Microsoft.Naming", "CA1720: IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public IReadOnlyList<int?> ParentReadOnlyListInterfaceOfNullableIntProperty { get; set; }
[SuppressMessage("Microsoft.Design", "CA1002: DoNotExposeGenericLists")]
[SuppressMessage("Microsoft.Naming", "CA1720: IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public IReadOnlyList<Guid?> ParentReadOnlyListInterfaceOfNullableGuidProperty { get; set; }
[SuppressMessage("Microsoft.Design", "CA1002: DoNotExposeGenericLists")]
[SuppressMessage("Microsoft.Naming", "CA1720: IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public IReadOnlyList<DateTime?> ParentReadOnlyListInterfaceOfNullableDateTimeProperty { get; set; }
[SuppressMessage("Microsoft.Design", "CA1002: DoNotExposeGenericLists")]
[SuppressMessage("Microsoft.Naming", "CA1720: IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public IReadOnlyList<CustomEnum?> ParentReadOnlyListInterfaceOfNullableCustomEnumProperty { get; set; }
[SuppressMessage("Microsoft.Design", "CA1002: DoNotExposeGenericLists")]
[SuppressMessage("Microsoft.Naming", "CA1720: IdentifiersShouldNotContainTypeNames")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms")]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
[SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public IReadOnlyList<CustomFlagsEnum?> ParentReadOnlyListInterfaceOfNullableCustomFlagsEnumProperty { get; set; }
}
} | 64.957143 | 229 | 0.729712 | [
"MIT"
] | OBeautifulCode/OBeautifulCode.CodeGen | OBeautifulCode.CodeGen.ModelObject.Test/Models/Scripted/All/PublicSet/ReadOnlyListOfNullable/ModelAllPublicSetReadOnlyListOfNullableParent.cs | 4,549 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Diagnostics;
using static Interop;
namespace System.Windows.Forms.PropertyGridInternal
{
internal partial class PropertyGridView
{
internal partial class MouseHook
{
/// <summary>
/// Forwards message hook calls.
/// </summary>
private class MouseHookObject
{
private readonly WeakReference _reference;
public MouseHookObject(MouseHook parent)
{
_reference = new WeakReference(parent, trackResurrection: false);
}
public virtual IntPtr Callback(User32.HC nCode, IntPtr wparam, IntPtr lparam)
{
IntPtr result = IntPtr.Zero;
try
{
if (_reference.Target is MouseHook hook)
{
result = hook.MouseHookProc(nCode, wparam, lparam);
}
}
catch (Exception ex)
{
Debug.Fail(ex.Message);
}
return result;
}
}
}
}
}
| 29.959184 | 93 | 0.493188 | [
"MIT"
] | ArtemTatarinov/winforms | src/System.Windows.Forms/src/System/Windows/Forms/PropertyGridInternal/PropertyGridView.MouseHook.MouseHookObject.cs | 1,470 | C# |
using System;
using System.Linq;
using System.Text;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using SampleSite.Identity;
using SampleSite.Identity.ManageViewModels;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace SampleSite.Controllers
{
public class ManageController : AccountController
{
private readonly UrlEncoder UrlEncoder;
private const string AuthenticatorUriFormat = "otpauth://totp/{0}:{1}?secret={2}&issuer={0}&digits=6";
private const string RecoveryCodesKey = nameof(RecoveryCodesKey);
[TempData]
public string StatusMessage { get; set; }
[HttpGet]
public async Task<IActionResult> UserData()
{
var user = await UserManager.GetUserAsync(User);
if (user == null)
{
throw new ApplicationException($"Unable to load user with ID '{UserManager.GetUserId(User)}'.");
}
var model = new IndexViewModel
{
Username = user.UserName,
Email = user.Email,
PhoneNumber = user.PhoneNumber,
IsEmailConfirmed = user.EmailConfirmed,
StatusMessage = StatusMessage
};
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> UserData(IndexViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await UserManager.GetUserAsync(User);
if (user == null)
{
throw new ApplicationException($"Unable to load user with ID '{UserManager.GetUserId(User)}'.");
}
var email = user.Email;
if (model.Email != email)
{
var setEmailResult = await UserManager.SetEmailAsync(user, model.Email);
if (!setEmailResult.Succeeded)
{
throw new ApplicationException($"Unexpected error occurred setting email for user with ID '{user.Id}'.");
}
}
var phoneNumber = user.PhoneNumber;
if (model.PhoneNumber != phoneNumber)
{
var setPhoneResult = await UserManager.SetPhoneNumberAsync(user, model.PhoneNumber);
if (!setPhoneResult.Succeeded)
{
throw new ApplicationException($"Unexpected error occurred setting phone number for user with ID '{user.Id}'.");
}
}
StatusMessage = "Your profile has been updated";
return RedirectToAction(nameof(UserData));
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> SendVerificationEmail(IndexViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await UserManager.GetUserAsync(User);
if (user == null)
{
throw new ApplicationException($"Unable to load user with ID '{UserManager.GetUserId(User)}'.");
}
var code = await UserManager.GenerateEmailConfirmationTokenAsync(user);
await EmailSender.SendMailConfirmationLink(user.Id.ToString(), code);
StatusMessage = "Verification email sent. Please check your email.";
return RedirectToAction(nameof(UserData));
}
[HttpGet]
public async Task<IActionResult> ChangePassword()
{
var user = await UserManager.GetUserAsync(User);
if (user == null)
{
throw new ApplicationException($"Unable to load user with ID '{UserManager.GetUserId(User)}'.");
}
var hasPassword = await UserManager.HasPasswordAsync(user);
if (!hasPassword)
{
return RedirectToAction(nameof(SetPassword));
}
var model = new ChangePasswordViewModel { StatusMessage = StatusMessage };
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ChangePassword(ChangePasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await UserManager.GetUserAsync(User);
if (user == null)
{
throw new ApplicationException($"Unable to load user with ID '{UserManager.GetUserId(User)}'.");
}
var changePasswordResult = await UserManager.ChangePasswordAsync(user, model.OldPassword, model.NewPassword);
if (!changePasswordResult.Succeeded)
{
AddErrors(changePasswordResult);
return View(model);
}
await SignInManager.SignInAsync(user, isPersistent: false);
Logger.LogInformation("User changed their password successfully.");
StatusMessage = "Your password has been changed.";
return RedirectToAction(nameof(ChangePassword));
}
[HttpGet]
public async Task<IActionResult> SetPassword()
{
var user = await UserManager.GetUserAsync(User);
if (user == null)
{
throw new ApplicationException($"Unable to load user with ID '{UserManager.GetUserId(User)}'.");
}
var hasPassword = await UserManager.HasPasswordAsync(user);
if (hasPassword)
{
return RedirectToAction(nameof(ChangePassword));
}
var model = new SetPasswordViewModel { StatusMessage = StatusMessage };
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> SetPassword(SetPasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await UserManager.GetUserAsync(User);
if (user == null)
{
throw new ApplicationException($"Unable to load user with ID '{UserManager.GetUserId(User)}'.");
}
var addPasswordResult = await UserManager.AddPasswordAsync(user, model.NewPassword);
if (!addPasswordResult.Succeeded)
{
AddErrors(addPasswordResult);
return View(model);
}
await SignInManager.SignInAsync(user, isPersistent: false);
StatusMessage = "Your password has been set.";
return RedirectToAction(nameof(SetPassword));
}
[HttpGet]
public async Task<IActionResult> ExternalLogins()
{
var user = await UserManager.GetUserAsync(User);
if (user == null)
{
throw new ApplicationException($"Unable to load user with ID '{UserManager.GetUserId(User)}'.");
}
var model = new ExternalLoginsViewModel { CurrentLogins = await UserManager.GetLoginsAsync(user) };
model.OtherLogins = (await SignInManager.GetExternalAuthenticationSchemesAsync())
.Where(auth => model.CurrentLogins.All(ul => auth.Name != ul.LoginProvider))
.ToList();
model.ShowRemoveButton = await UserManager.HasPasswordAsync(user) || model.CurrentLogins.Count > 1;
model.StatusMessage = StatusMessage;
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> LinkLogin(string provider)
{
// Clear the existing external cookie to ensure a clean login process
await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);
// Request a redirect to the external login provider to link a login for the current user
var redirectUrl = Url.Action(nameof(LinkLoginCallback));
var properties = SignInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl, UserManager.GetUserId(User));
return new ChallengeResult(provider, properties);
}
[HttpGet]
public async Task<IActionResult> LinkLoginCallback()
{
var user = await UserManager.GetUserAsync(User);
if (user == null)
{
throw new ApplicationException($"Unable to load user with ID '{UserManager.GetUserId(User)}'.");
}
var info = await SignInManager.GetExternalLoginInfoAsync(user.Id.ToString());
if (info == null)
{
throw new ApplicationException($"Unexpected error occurred loading external login info for user with ID '{user.Id}'.");
}
var result = await UserManager.AddLoginAsync(user, info);
if (!result.Succeeded)
{
throw new ApplicationException($"Unexpected error occurred adding external login for user with ID '{user.Id}'.");
}
// Clear the existing external cookie to ensure a clean login process
await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);
StatusMessage = "The external login was added.";
return RedirectToAction(nameof(ExternalLogins));
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> RemoveLogin(RemoveLoginViewModel model)
{
var user = await UserManager.GetUserAsync(User);
if (user == null)
{
throw new ApplicationException($"Unable to load user with ID '{UserManager.GetUserId(User)}'.");
}
var result = await UserManager.RemoveLoginAsync(user, model.LoginProvider, model.ProviderKey);
if (!result.Succeeded)
{
throw new ApplicationException($"Unexpected error occurred removing external login for user with ID '{user.Id}'.");
}
await SignInManager.SignInAsync(user, isPersistent: false);
StatusMessage = "The external login was removed.";
return RedirectToAction(nameof(ExternalLogins));
}
[HttpGet]
public async Task<IActionResult> TwoFactorAuthentication()
{
var user = await UserManager.GetUserAsync(User);
if (user == null)
{
throw new ApplicationException($"Unable to load user with ID '{UserManager.GetUserId(User)}'.");
}
var model = new TwoFactorAuthenticationViewModel
{
HasAuthenticator = await UserManager.GetAuthenticatorKeyAsync(user) != null,
Is2faEnabled = user.TwoFactorEnabled,
RecoveryCodesLeft = await UserManager.CountRecoveryCodesAsync(user),
};
return View(model);
}
[HttpGet]
public async Task<IActionResult> Disable2faWarning()
{
var user = await UserManager.GetUserAsync(User);
if (user == null)
{
throw new ApplicationException($"Unable to load user with ID '{UserManager.GetUserId(User)}'.");
}
if (!user.TwoFactorEnabled)
{
throw new ApplicationException($"Unexpected error occured disabling 2FA for user with ID '{user.Id}'.");
}
return View(nameof(Disable2fa));
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Disable2fa()
{
var user = await UserManager.GetUserAsync(User);
if (user == null)
{
throw new ApplicationException($"Unable to load user with ID '{UserManager.GetUserId(User)}'.");
}
var disable2faResult = await UserManager.SetTwoFactorEnabledAsync(user, false);
if (!disable2faResult.Succeeded)
{
throw new ApplicationException($"Unexpected error occured disabling 2FA for user with ID '{user.Id}'.");
}
Logger.LogInformation("User with ID {UserId} has disabled 2fa.", user.Id);
return RedirectToAction(nameof(TwoFactorAuthentication));
}
[HttpGet]
public async Task<IActionResult> EnableAuthenticator()
{
var user = await UserManager.GetUserAsync(User);
if (user == null)
{
throw new ApplicationException($"Unable to load user with ID '{UserManager.GetUserId(User)}'.");
}
var model = new EnableAuthenticatorViewModel();
await LoadSharedKeyAndQrCodeUriAsync(user, model);
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> EnableAuthenticator(EnableAuthenticatorViewModel model)
{
var user = await UserManager.GetUserAsync(User);
if (user == null)
{
throw new ApplicationException($"Unable to load user with ID '{UserManager.GetUserId(User)}'.");
}
if (!ModelState.IsValid)
{
await LoadSharedKeyAndQrCodeUriAsync(user, model);
return View(model);
}
// Strip spaces and hypens
var verificationCode = model.Code.Replace(" ", string.Empty).Replace("-", string.Empty);
var is2faTokenValid = await UserManager.VerifyTwoFactorTokenAsync(
user, UserManager.Options.Tokens.AuthenticatorTokenProvider, verificationCode);
if (!is2faTokenValid)
{
ModelState.AddModelError("Code", "Verification code is invalid.");
await LoadSharedKeyAndQrCodeUriAsync(user, model);
return View(model);
}
await UserManager.SetTwoFactorEnabledAsync(user, true);
Logger.LogInformation("User with ID {UserId} has enabled 2FA with an authenticator app.", user.Id);
var recoveryCodes = await UserManager.GenerateNewTwoFactorRecoveryCodesAsync(user, 10);
TempData[RecoveryCodesKey] = recoveryCodes.ToArray();
return RedirectToAction(nameof(ShowRecoveryCodes));
}
[HttpGet]
public IActionResult ShowRecoveryCodes()
{
var recoveryCodes = (string[])TempData[RecoveryCodesKey];
if (recoveryCodes == null)
{
return RedirectToAction(nameof(TwoFactorAuthentication));
}
var model = new ShowRecoveryCodesViewModel { RecoveryCodes = recoveryCodes };
return View(model);
}
[HttpGet]
public IActionResult ResetAuthenticatorWarning()
{
return View(nameof(ResetAuthenticator));
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ResetAuthenticator()
{
var user = await UserManager.GetUserAsync(User);
if (user == null)
{
throw new ApplicationException($"Unable to load user with ID '{UserManager.GetUserId(User)}'.");
}
await UserManager.SetTwoFactorEnabledAsync(user, false);
await UserManager.ResetAuthenticatorKeyAsync(user);
Logger.LogInformation("User with id '{UserId}' has reset their authentication app key.", user.Id);
return RedirectToAction(nameof(EnableAuthenticator));
}
[HttpGet]
public async Task<IActionResult> GenerateRecoveryCodesWarning()
{
var user = await UserManager.GetUserAsync(User);
if (user == null)
{
throw new ApplicationException($"Unable to load user with ID '{UserManager.GetUserId(User)}'.");
}
if (!user.TwoFactorEnabled)
{
throw new ApplicationException($"Cannot generate recovery codes for user with ID '{user.Id}' because they do not have 2FA enabled.");
}
return View(nameof(GenerateRecoveryCodes));
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> GenerateRecoveryCodes()
{
var user = await UserManager.GetUserAsync(User);
if (user == null)
{
throw new ApplicationException($"Unable to load user with ID '{UserManager.GetUserId(User)}'.");
}
if (!user.TwoFactorEnabled)
{
throw new ApplicationException($"Cannot generate recovery codes for user with ID '{user.Id}' as they do not have 2FA enabled.");
}
var recoveryCodes = await UserManager.GenerateNewTwoFactorRecoveryCodesAsync(user, 10);
Logger.LogInformation("User with ID {UserId} has generated new 2FA recovery codes.", user.Id);
var model = new ShowRecoveryCodesViewModel { RecoveryCodes = recoveryCodes.ToArray() };
return View(nameof(ShowRecoveryCodes), model);
}
#region Helpers
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
private string FormatKey(string unformattedKey)
{
var result = new StringBuilder();
int currentPosition = 0;
while (currentPosition + 4 < unformattedKey.Length)
{
result.Append(unformattedKey.Substring(currentPosition, 4)).Append(" ");
currentPosition += 4;
}
if (currentPosition < unformattedKey.Length)
{
result.Append(unformattedKey.Substring(currentPosition));
}
return result.ToString().ToLowerInvariant();
}
private string GenerateQrCodeUri(string email, string unformattedKey)
{
return string.Format(
AuthenticatorUriFormat,
UrlEncoder.Encode("IdentityDemo"),
UrlEncoder.Encode(email),
unformattedKey);
}
private async Task LoadSharedKeyAndQrCodeUriAsync(TestSiteUser user, EnableAuthenticatorViewModel model)
{
var unformattedKey = await UserManager.GetAuthenticatorKeyAsync(user);
if (string.IsNullOrEmpty(unformattedKey))
{
await UserManager.ResetAuthenticatorKeyAsync(user);
unformattedKey = await UserManager.GetAuthenticatorKeyAsync(user);
}
model.SharedKey = FormatKey(unformattedKey);
model.AuthenticatorUri = GenerateQrCodeUri(user.Email, unformattedKey);
}
#endregion
}
}
| 36.901923 | 149 | 0.585492 | [
"MIT"
] | BuzzDee3000/AspNetCore.Identity.Mongo | SelfCheck/Controllers/ManageController.cs | 19,191 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Changes to this file will be lost if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading;
using System.Web;
using System.Web.Caching;
using System.Xml;
using Havit.Business;
using Havit.Business.Query;
using Havit.Collections;
using Havit.Data;
using Havit.Data.SqlServer;
using Havit.Data.SqlTypes;
namespace Havit.BusinessLayerTest
{
/// <summary>
/// Kolekce business objektů typu Havit.BusinessLayerTest.RoleLocalization.
/// </summary>
[System.CodeDom.Compiler.GeneratedCode("Havit.BusinessLayerGenerator", "1.0")]
public partial class RoleLocalizationCollectionBase : BusinessObjectCollection<RoleLocalization, RoleLocalizationCollection>, ILocalizationCollection
{
#region Constructors
/// <summary>
/// Vytvoří novou instanci kolekce.
/// </summary>
public RoleLocalizationCollectionBase() : base()
{
}
/// <summary>
/// Vytvoří novou instanci kolekce a zkopíruje do ní prvky z předané kolekce.
/// </summary>
public RoleLocalizationCollectionBase(IEnumerable<RoleLocalization> collection) : base(collection)
{
}
#endregion
#region Find & FindAll
/// <summary>
/// Prohledá kolekci a vrátí první nalezený prvek odpovídající kritériu match.
/// </summary>
public override RoleLocalization Find(Predicate<RoleLocalization> match)
{
LoadAll();
return base.Find(match);
}
/// <summary>
/// Prohledá kolekci a vrátí všechny prvky odpovídající kritériu match.
/// </summary>
public override RoleLocalizationCollection FindAll(Predicate<RoleLocalization> match)
{
LoadAll();
return base.FindAll(match);
}
#endregion
#region Sort
/// <summary>
/// Seřadí prvky kolekce dle požadované property, která implementuje IComparable.
/// </summary>
/// <remarks>
/// Používá Havit.Collections.GenericPropertyComparer{T}. K porovnávání podle property
/// tedy dochází pomocí reflexe - relativně pomalu. Pokud je potřeba vyšší výkon, je potřeba použít
/// overload Sort(Generic Comparsion) s přímým přístupem k property.
/// </remarks>
/// <param name="propertyName">property, podle které se má řadit</param>
/// <param name="ascending">true, pokud se má řadit vzestupně, false, pokud sestupně</param>
[Obsolete]
public override void Sort(string propertyName, bool ascending)
{
LoadAll();
base.Sort(propertyName, ascending);
}
/// <summary>
/// Seřadí prvky kolekce dle požadované property, která implementuje IComparable.
/// Před řazením načtě všechny prvky metodou LoadAll.
/// </summary>
/// <remarks>
/// Používá Havit.Collections.GenericPropertyComparer{T}. K porovnávání podle property
/// tedy dochází pomocí reflexe - relativně pomalu. Pokud je potřeba vyšší výkon, je potřeba použít
/// overload Sort(Generic Comparsion) s přímým přístupem k property.
/// </remarks>
/// <param name="propertyInfo">Property, podle které se má řadit.</param>
/// <param name="sortDirection">Směr řazení.</param>
public override void Sort(PropertyInfo propertyInfo, SortDirection sortDirection)
{
LoadAll();
base.Sort(propertyInfo, sortDirection);
}
/// <summary>
/// Seřadí prvky kolekce dle zadaného srovnání. Publikuje metodu Sort(Generic Comparsion) inner-Listu.
/// Před řazením načtě všechny prvky metodou LoadAll.
/// </summary>
/// <param name="comparsion">srovnání, podle kterého mají být prvky seřazeny</param>
public override void Sort(Comparison<RoleLocalization> comparsion)
{
LoadAll();
base.Sort(comparsion);
}
#endregion
#region LoadAll
/// <summary>
/// Načte všechny prvky kolekce.
/// </summary>
public void LoadAll()
{
LoadAll(null);
}
/// <summary>
/// Načte všechny prvky kolekce.
/// </summary>
public void LoadAll(DbTransaction transaction)
{
if ((!LoadAllRequired) || (this.Count == 0))
{
return;
}
Dictionary<int, RoleLocalization> ghosts = new Dictionary<int, RoleLocalization>();
for (int i = 0; i < this.Count; i++)
{
RoleLocalization currentObject = this[i];
if ((currentObject != null) && (!currentObject.IsLoaded))
{
if (!ghosts.ContainsKey(currentObject.ID))
{
ghosts.Add(currentObject.ID, currentObject);
}
}
}
if (ghosts.Count > 0)
{
DbCommand dbCommand = DbConnector.Default.ProviderFactory.CreateCommand();
dbCommand.Transaction = transaction;
QueryParams queryParams = new QueryParams();
queryParams.ObjectInfo = RoleLocalization.ObjectInfo;
queryParams.Conditions.Add(ReferenceCondition.CreateIn(RoleLocalization.Properties.ID, ghosts.Keys.ToArray()));
queryParams.IncludeDeleted = true;
queryParams.PrepareCommand(dbCommand, SqlServerPlatform.SqlServer2008, CommandBuilderOptions.None);
using (DbDataReader reader = DbConnector.Default.ExecuteReader(dbCommand))
{
while (reader.Read())
{
DataRecord dataRecord = new DataRecord(reader, queryParams.GetDataLoadPower());
int id = dataRecord.Get<int>(RoleLocalization.Properties.ID.FieldName);
RoleLocalization ghost = ghosts[id];
if (!ghost.IsLoaded)
{
ghost.Load(dataRecord);
}
}
}
}
LoadAllRequired = false;
}
#endregion
#region Localizations
/// <summary>
/// Vrací objekt s lokalizovanými daty na základě jazyka, který je předán.
/// </summary>
public RoleLocalization this[Havit.BusinessLayerTest.Language language]
{
get
{
return this.Find(delegate(RoleLocalization item)
{
return (item.Language == language);
});
}
}
/// <summary>
/// Vrací objekt s lokalizovanými daty na základě aktuálního jazyka (aktuální jazyk se hledá na základě CurrentUICulture).
/// </summary>
public virtual RoleLocalization Current
{
get
{
return this[Havit.BusinessLayerTest.Language.Current];
}
}
/// <summary>
/// Vrací objekt s lokalizovanými daty na základě jazyka, který je předán.
/// </summary>
BusinessObjectBase ILocalizationCollection.this[ILanguage language]
{
get
{
return this[(Havit.BusinessLayerTest.Language)language];
}
}
/// <summary>
/// Vrací objekt s lokalizovanými daty na základě aktuálního jazyka (aktuální jazyk se hledá na základě CurrentUICulture).
/// </summary>
BusinessObjectBase ILocalizationCollection.Current
{
get
{
return this.Current;
}
}
#endregion
}
}
| 29.412766 | 150 | 0.685909 | [
"MIT"
] | havit/HavitFramework | BusinessLayerTest/_generated/RoleLocalizationCollectionBase.cs | 7,072 | C# |
using Disqord.Models;
namespace Disqord
{
public abstract class CachedNestedChannel : CachedGuildChannel, IGuildChannel
{
public CachedCategoryChannel Category
{
get
{
var categoryId = CategoryId;
return categoryId != null
? Guild.GetCategoryChannel(categoryId.Value)
: null;
}
}
public Snowflake? CategoryId { get; private set; }
internal CachedNestedChannel(DiscordClient client, ChannelModel model, CachedGuild guild) : base(client, model, guild)
{ }
internal override void Update(ChannelModel model)
{
if (model.ParentId.HasValue)
CategoryId = model.ParentId.Value;
base.Update(model);
}
public override string ToString()
=> Name;
}
} | 27.352941 | 127 | 0.541935 | [
"MIT"
] | Anu6is/Disqord | src/Disqord/Entities/Channels/Guild/CachedNestedChannel.cs | 932 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FindCaveRoute
{
class Extensions
{
}
}
| 13.285714 | 33 | 0.709677 | [
"Apache-2.0"
] | ArranSmedley/Dijkstras-algorithm- | FindCaveRoute/Extensions.cs | 188 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// <auto-generated/>
// Template Source: StreamRequest.cs.tt
namespace Microsoft.Graph
{
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading;
/// <summary>
/// The type ProfilePhotoContentRequest.
/// </summary>
public partial class ProfilePhotoContentRequest : BaseRequest, IProfilePhotoContentRequest
{
/// <summary>
/// Constructs a new ProfilePhotoContentRequest.
/// <param name="requestUrl">The request URL.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="options">Query option name value pairs for the request.</param>
/// </summary>
public ProfilePhotoContentRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Gets the stream.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <param name="completionOption">The <see cref="HttpCompletionOption"/> to pass to the <see cref="IHttpProvider"/> on send.</param>
/// <returns>The stream.</returns>
public System.Threading.Tasks.Task<Stream> GetAsync(CancellationToken cancellationToken = default, HttpCompletionOption completionOption = HttpCompletionOption.ResponseContentRead)
{
this.Method = HttpMethods.GET;
return this.SendStreamRequestAsync(null, cancellationToken, completionOption);
}
/// <summary>
/// Gets the <see cref="GraphResponse"/> object of the request.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <param name="completionOption">The <see cref="HttpCompletionOption"/> to pass to the <see cref="IHttpProvider"/> on send.</param>
/// <returns>The <see cref="GraphResponse"/> object of the request.</returns>
public System.Threading.Tasks.Task<GraphResponse> GetResponseAsync(CancellationToken cancellationToken = default, HttpCompletionOption completionOption = HttpCompletionOption.ResponseContentRead)
{
this.Method = HttpMethods.GET;
return this.SendAsyncWithGraphResponse(null, cancellationToken, completionOption);
}
/// <summary>
/// PUTs the specified stream.
/// </summary>
/// <param name="content">The stream to PUT.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <param name="completionOption">The <see cref="HttpCompletionOption"/> to pass to the <see cref="IHttpProvider"/> on send.</param>
/// <returns>The updated stream.</returns>
public System.Threading.Tasks.Task<Stream> PutAsync(Stream content, CancellationToken cancellationToken = default, HttpCompletionOption completionOption = HttpCompletionOption.ResponseContentRead)
{
this.ContentType ??= CoreConstants.MimeTypeNames.Application.Stream;
this.Method = HttpMethods.PUT;
return this.SendStreamRequestAsync(content, cancellationToken, completionOption);
}
/// <summary>
/// PUTs the specified stream and returns a <see cref="GraphResponse"/> object.
/// </summary>
/// <param name="content">The stream to PUT.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <param name="completionOption">The <see cref="HttpCompletionOption"/> to pass to the <see cref="IHttpProvider"/> on send.</param>
/// <returns>The <see cref="GraphResponse"/> object returned by the PUT call.</returns>
public System.Threading.Tasks.Task<GraphResponse> PutResponseAsync(Stream content, CancellationToken cancellationToken = default, HttpCompletionOption completionOption = HttpCompletionOption.ResponseContentRead)
{
this.ContentType ??= CoreConstants.MimeTypeNames.Application.Stream;
this.Method = HttpMethods.PUT;
return this.SendAsyncWithGraphResponse(content, cancellationToken, completionOption);
}
}
}
| 53.088889 | 219 | 0.646505 | [
"MIT"
] | ScriptBox99/msgraph-beta-sdk-dotnet | src/Microsoft.Graph/Generated/requests/ProfilePhotoContentRequest.cs | 4,778 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Connections;
using Microsoft.AspNetCore.Http.Connections;
using Microsoft.AspNetCore.Http.Connections.Internal;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
namespace Microsoft.AspNetCore.Builder;
/// <summary>
/// Extension methods on <see cref="IEndpointRouteBuilder"/> that add routes for <see cref="ConnectionHandler"/>s.
/// </summary>
public static class ConnectionEndpointRouteBuilderExtensions
{
private static readonly NegotiateMetadata _negotiateMetadata = new NegotiateMetadata();
/// <summary>
/// Maps incoming requests with the specified path to the provided connection pipeline.
/// </summary>
/// <param name="endpoints">The <see cref="IEndpointRouteBuilder"/> to add the route to.</param>
/// <param name="pattern">The route pattern.</param>
/// <param name="configure">A callback to configure the connection.</param>
/// <returns>An <see cref="ConnectionEndpointRouteBuilder"/> for endpoints associated with the connections.</returns>
public static ConnectionEndpointRouteBuilder MapConnections(this IEndpointRouteBuilder endpoints, string pattern, Action<IConnectionBuilder> configure) =>
endpoints.MapConnections(pattern, new HttpConnectionDispatcherOptions(), configure);
/// <summary>
/// Maps incoming requests with the specified path to the provided connection pipeline.
/// </summary>
/// <typeparam name="TConnectionHandler">The <see cref="ConnectionHandler"/> type.</typeparam>
/// <param name="endpoints">The <see cref="IEndpointRouteBuilder"/> to add the route to.</param>
/// <param name="pattern">The route pattern.</param>
/// <returns>An <see cref="ConnectionEndpointRouteBuilder"/> for endpoints associated with the connections.</returns>
public static ConnectionEndpointRouteBuilder MapConnectionHandler<TConnectionHandler>(this IEndpointRouteBuilder endpoints, string pattern) where TConnectionHandler : ConnectionHandler
{
return endpoints.MapConnectionHandler<TConnectionHandler>(pattern, configureOptions: null);
}
/// <summary>
/// Maps incoming requests with the specified path to the provided connection pipeline.
/// </summary>
/// <typeparam name="TConnectionHandler">The <see cref="ConnectionHandler"/> type.</typeparam>
/// <param name="endpoints">The <see cref="IEndpointRouteBuilder"/> to add the route to.</param>
/// <param name="pattern">The route pattern.</param>
/// <param name="configureOptions">A callback to configure dispatcher options.</param>
/// <returns>An <see cref="ConnectionEndpointRouteBuilder"/> for endpoints associated with the connections.</returns>
public static ConnectionEndpointRouteBuilder MapConnectionHandler<TConnectionHandler>(this IEndpointRouteBuilder endpoints, string pattern, Action<HttpConnectionDispatcherOptions>? configureOptions) where TConnectionHandler : ConnectionHandler
{
var options = new HttpConnectionDispatcherOptions();
configureOptions?.Invoke(options);
var conventionBuilder = endpoints.MapConnections(pattern, options, b =>
{
b.UseConnectionHandler<TConnectionHandler>();
});
var attributes = typeof(TConnectionHandler).GetCustomAttributes(inherit: true);
conventionBuilder.Add(e =>
{
// Add all attributes on the ConnectionHandler has metadata (this will allow for things like)
// auth attributes and cors attributes to work seamlessly
foreach (var item in attributes)
{
e.Metadata.Add(item);
}
});
return conventionBuilder;
}
/// <summary>
/// Maps incoming requests with the specified path to the provided connection pipeline.
/// </summary>
/// <param name="endpoints">The <see cref="IEndpointRouteBuilder"/> to add the route to.</param>
/// <param name="pattern">The route pattern.</param>
/// <param name="options">Options used to configure the connection.</param>
/// <param name="configure">A callback to configure the connection.</param>
/// <returns>An <see cref="ConnectionEndpointRouteBuilder"/> for endpoints associated with the connections.</returns>
public static ConnectionEndpointRouteBuilder MapConnections(this IEndpointRouteBuilder endpoints, string pattern, HttpConnectionDispatcherOptions options, Action<IConnectionBuilder> configure)
{
var dispatcher = endpoints.ServiceProvider.GetRequiredService<HttpConnectionDispatcher>();
var connectionBuilder = new ConnectionBuilder(endpoints.ServiceProvider);
configure(connectionBuilder);
var connectionDelegate = connectionBuilder.Build();
// REVIEW: Consider expanding the internals of the dispatcher as endpoint routes instead of
// using if statements we can let the matcher handle
var conventionBuilders = new List<IEndpointConventionBuilder>();
// Build the negotiate application
var app = endpoints.CreateApplicationBuilder();
app.UseWebSockets();
app.Run(c => dispatcher.ExecuteNegotiateAsync(c, options));
var negotiateHandler = app.Build();
var negotiateBuilder = endpoints.Map(pattern + "/negotiate", negotiateHandler);
conventionBuilders.Add(negotiateBuilder);
// Add the negotiate metadata so this endpoint can be identified
negotiateBuilder.WithMetadata(_negotiateMetadata);
negotiateBuilder.WithMetadata(options);
// build the execute handler part of the protocol
app = endpoints.CreateApplicationBuilder();
app.UseWebSockets();
app.Run(c => dispatcher.ExecuteAsync(c, options, connectionDelegate));
var executehandler = app.Build();
var executeBuilder = endpoints.Map(pattern, executehandler);
conventionBuilders.Add(executeBuilder);
var compositeConventionBuilder = new CompositeEndpointConventionBuilder(conventionBuilders);
// Add metadata to all of Endpoints
compositeConventionBuilder.Add(e =>
{
// Add the authorization data as metadata
foreach (var data in options.AuthorizationData)
{
e.Metadata.Add(data);
}
});
return new ConnectionEndpointRouteBuilder(compositeConventionBuilder);
}
private class CompositeEndpointConventionBuilder : IEndpointConventionBuilder
{
private readonly List<IEndpointConventionBuilder> _endpointConventionBuilders;
public CompositeEndpointConventionBuilder(List<IEndpointConventionBuilder> endpointConventionBuilders)
{
_endpointConventionBuilders = endpointConventionBuilders;
}
public void Add(Action<EndpointBuilder> convention)
{
foreach (var endpointConventionBuilder in _endpointConventionBuilders)
{
endpointConventionBuilder.Add(convention);
}
}
}
}
| 47.94702 | 247 | 0.714641 | [
"MIT"
] | JackyFei/aspnetcore | src/SignalR/common/Http.Connections/src/ConnectionEndpointRouteBuilderExtensions.cs | 7,240 | C# |
using AppDynamics.Extension.SDK;
using AppDynamics.Extension.SDK.Model.Enumeration;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace AppDynamics.Infrastructure.Framework.Extension
{
public class ExtensionActivator
{
private static NLog.Logger _logger = NLog.LogManager.GetCurrentClassLogger();
public static IExtension CreateExtensionInstance(string executionPath, string extensionType,
string executionType, string executionMode, string xmlFilePath)
{
IExtension extobj = null;
Type type = getTypeStr(executionPath, executionType, xmlFilePath);
if (type != null)
{
// Let this throw exception, if can not create object of type
extobj = (IExtension)System.Activator.CreateInstance(type);
}
if (extobj != null)
{
extobj.ExecutionMode = (ExecutionMode)Enum.Parse(typeof(ExecutionMode), executionMode, true);
extobj.ExecutionType = (ExecutionType)Enum.Parse(typeof(ExecutionType), executionType, true);
extobj.Type = (ExtensionType)Enum.Parse(typeof(ExtensionType), extensionType, true);
}
else
{
throw new ExtensionFrameworkException(String.Format(
"Could not create object of type {0}", executionPath));
}
return extobj;
}
/// <summary>
/// Returns type string for creating extensions both internal and external.
/// </summary>
/// <param name="executionPath"></param>
/// <param name="extensionType"></param>
/// <param name="executionType"></param>
/// <param name="executionMode"></param>
/// <returns></returns>
private static Type getTypeStr(string executionPath, string executionType, string xmlFilePath)
{
Type type = null;
if (executionType.Equals(ExecutionType.SCRIPT.ToString(), StringComparison.CurrentCultureIgnoreCase))
{
// Only for script execution, coz execution path contains script path not dll pointer
// #scriptExtension
_logger.Trace(String.Format("changing execution path for script extension-{0}", executionPath));
executionPath = ExecutionType.SCRIPT.ToString().ToLower();
}
string typeString = "";
if (!ResourceStrings.InternalExtensions.TryGetValue(executionPath, out typeString))
{
// for external extension, execution path should be equal to type string.
typeString = executionPath;
// WIP: need to make sure that the dlls present in extension directory are loaded
// Without dlls loaded, activator will fail to create object
type = loadAssemblies(xmlFilePath, executionPath);
}
else
{
type = Type.GetType(typeString);
}
return type;
}
private static Type loadAssemblies(string xmlPath, string executionPath)
{
Type type = null;
string directoryPath = xmlPath.Replace(ResourceStrings.ExtensionXmlName, "");
if (Directory.Exists(directoryPath))
{
// #IMP- Loading all assemblies in directory
foreach (string fileName in Directory.GetFiles(directoryPath, "*.dll", SearchOption.TopDirectoryOnly))
{
System.Reflection.Assembly a = System.Reflection.Assembly.LoadFrom(fileName);
foreach (Type t in a.GetTypes())
{
if (t.Name.Equals(executionPath, StringComparison.InvariantCultureIgnoreCase)
|| t.FullName.Equals(executionPath, StringComparison.InvariantCultureIgnoreCase))
{
type = t;
break;
}
}
}
}
return type;
}
}
}
| 37.367521 | 119 | 0.557868 | [
"Apache-2.0"
] | Appdynamics/DotNetAgentExtensionManager | Source/AppDynamics.Extension.Manager/AppDynamics.Extension.Infrastructure/Framework/Extension/ExtensionActivator.cs | 4,374 | C# |
using Core.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ExampleManager
{
[ExampleClass(Description = "Lambda Method Running Example")]
class TestLambdaMethod
{
[ExampleMethod]
static void Main(string[] args)
{
Action a = () => { Console.WriteLine("I called you!!"); };
a();
}
}
}
| 20.545455 | 70 | 0.623894 | [
"MIT"
] | geegee4iee/example-manager | ExampleManager/RuntimeSource/TestLambdaMethod.cs | 454 | 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 DBScan.Properties
{
/// <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 Resources
{
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources()
{
}
/// <summary>
/// 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 ((resourceMan == null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("DBScan.Properties.Resources", typeof(Resources).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;
}
}
}
}
| 38.458333 | 172 | 0.601661 | [
"MIT"
] | izzettunc/dbscan | DBScan/Properties/Resources.Designer.cs | 2,771 | C# |
using System.IdentityModel.Tokens.Jwt;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
namespace smart_app
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
services.AddAuthentication(options =>
{
options.DefaultScheme = "Cookies";
options.DefaultChallengeScheme = "oidc";
})
.AddCookie("Cookies")
.AddOpenIdConnect("oidc", options =>
{
options.SignInScheme = "Cookies";
options.Authority = "http://localhost:5000";
options.RequireHttpsMetadata = false;
options.ClientId = "7d26357a-6904-4b93-8759-b53f635a6241";
options.ClientSecret = "secret";
options.ResponseType = "code id_token";
options.SaveTokens = true;
options.GetClaimsFromUserInfoEndpoint = true;
options.Scope.Add("api1");
//options.Scope.Add("offline_access");
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
//else
//{
// app.UseExceptionHandler("/Home/Error");
//}
app.UseAuthentication();
app.UseStaticFiles();
app.UseMvcWithDefaultRoute();
}
}
}
| 32.83871 | 122 | 0.579568 | [
"BSD-3-Clause"
] | brianpos/smart-on-fhir | src/smart-app/Startup.cs | 2,038 | C# |
namespace TrinketDigitalSecurity
{
public partial class F_M_Four_05 : Form
{
public F_M_Four_05()
{
InitializeComponent();
}
private void btn_exit_Click(object sender, EventArgs e)
{
Close();
}
private void btn_next_Click(object sender, EventArgs e)
{
Hide();
F_M_Four_06 f_M_Four_06 = new F_M_Four_06();
f_M_Four_06.ShowDialog();
Close();
}
private void btn_back_Click(object sender, EventArgs e)
{
Hide();
F_M_Four_04 f_M_Four_04 = new F_M_Four_04();
f_M_Four_04.ShowDialog();
Close();
}
}
}
| 22.6875 | 63 | 0.520661 | [
"MIT"
] | danhpaiva/bugiganga-digital-security | TrinketDigitalSecurity/forms/module_four/F_M_Four_05.cs | 728 | C# |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using Microsoft.Azure.Commands.Common.Authentication;
namespace Microsoft.WindowsAzure.Commands.Storage.Blob.Cmdlet
{
using Adapters;
using Azure.Commands.Common.Authentication.Abstractions;
using Commands.Common;
using Commands.Common.Storage.ResourceModel;
using Microsoft.WindowsAzure.Commands.Common.Storage;
using Microsoft.WindowsAzure.Commands.Storage.Common;
using Microsoft.WindowsAzure.Commands.Storage.File;
using Microsoft.WindowsAzure.Commands.Storage.Model.Contract;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using Microsoft.WindowsAzure.Storage.File;
using System;
using System.IO;
using System.Management.Automation;
using System.Reflection;
using System.Security.Permissions;
using System.Threading.Tasks;
[Microsoft.Azure.PowerShell.Cmdlets.Storage.Profile("hybrid-2019-03-01")]
[Cmdlet("Start", Azure.Commands.ResourceManager.Common.AzureRMConstants.AzurePrefix + "StorageBlobCopy!V1", SupportsShouldProcess = true, DefaultParameterSetName = ContainerNameParameterSet),OutputType(typeof(AzureStorageBlob))]
[Alias("Start-CopyAzureStorageBlob")]
public class StartAzureStorageBlobCopy : StorageDataMovementCmdletBase, IModuleAssemblyInitializer
{
private const string BlobTypeMismatch = "Blob type of the blob reference doesn't match blob type of the blob.";
/// <summary>
/// Blob Pipeline parameter set name
/// </summary>
private const string BlobParameterSet = "BlobInstance";
/// <summary>
/// Blob Pipeline parameter set name
/// </summary>
private const string BlobToBlobParameterSet = "BlobInstanceToBlobInstance";
/// <summary>
/// Container pipeline paremeter set name
/// </summary>
private const string ContainerParameterSet = "ContainerInstance";
/// <summary>
/// Blob name and container name parameter set
/// </summary>
private const string ContainerNameParameterSet = "ContainerName";
/// <summary>
/// To copy from file with share name and file path to a blob represent with container name and blob name.
/// </summary>
private const string ShareNameParameterSet = "ShareName";
/// <summary>
/// To copy from file with share instance and file path to a blob represent with container name and blob name.
/// </summary>
private const string ShareParameterSet = "ShareInstance";
/// <summary>
/// To copy from file with file directory instance and file path to a blob with container name and blob name.
/// </summary>
private const string DirParameterSet = "DirInstance";
/// <summary>
/// To copy from file with file instance to a blob with container name and blob name.
/// </summary>
private const string FileParameterSet = "FileInstance";
/// <summary>
/// To copy from file with file instance to a blob with blob instance.
/// </summary>
private const string FileToBlobParameterSet = "FileInstanceToBlobInstance";
/// <summary>
/// Source uri parameter set
/// </summary>
private const string UriParameterSet = "UriPipeline";
[Alias("SrcICloudBlob", "SrcCloudBlob", "ICloudBlob", "SourceICloudBlob", "SourceCloudBlob")]
[Parameter(HelpMessage = "CloudBlob Object", Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = BlobParameterSet)]
[Parameter(HelpMessage = "CloudBlob Object", Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = BlobToBlobParameterSet)]
public CloudBlob CloudBlob { get; set; }
[Alias("SourceCloudBlobContainer")]
[Parameter(HelpMessage = "CloudBlobContainer Object", Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = ContainerParameterSet)]
public CloudBlobContainer CloudBlobContainer { get; set; }
[Alias("SourceBlob")]
[Parameter(HelpMessage = "Blob name", ParameterSetName = ContainerParameterSet, Mandatory = true, Position = 0)]
[Parameter(HelpMessage = "Blob name", ParameterSetName = ContainerNameParameterSet, Mandatory = true, Position = 0)]
public string SrcBlob
{
get { return BlobName; }
set { BlobName = value; }
}
private string BlobName = String.Empty;
[Alias("SourceContainer")]
[Parameter(HelpMessage = "Source Container name", Mandatory = true, ParameterSetName = ContainerNameParameterSet)]
[ValidateNotNullOrEmpty]
public string SrcContainer
{
get { return ContainerName; }
set { ContainerName = value; }
}
private string ContainerName = String.Empty;
[Alias("SourceShareName")]
[Parameter(HelpMessage = "Source share name", Mandatory = true, ParameterSetName = ShareNameParameterSet)]
[ValidateNotNullOrEmpty]
public string SrcShareName { get; set; }
[Alias("SourceShare")]
[Parameter(HelpMessage = "Source share", Mandatory = true, ParameterSetName = ShareParameterSet)]
[ValidateNotNull]
public CloudFileShare SrcShare { get; set; }
[Alias("SourceDir")]
[Parameter(HelpMessage = "Source file directory", Mandatory = true, ParameterSetName = DirParameterSet)]
[ValidateNotNull]
public CloudFileDirectory SrcDir { get; set; }
[Alias("SourceFilePath")]
[Parameter(HelpMessage = "Source file path", Mandatory = true, ParameterSetName = ShareNameParameterSet)]
[Parameter(HelpMessage = "Source file path", Mandatory = true, ParameterSetName = ShareParameterSet)]
[Parameter(HelpMessage = "Source file path", Mandatory = true, ParameterSetName = DirParameterSet)]
[ValidateNotNullOrEmpty]
public string SrcFilePath { get; set; }
[Alias("SourceFile")]
[Parameter(HelpMessage = "Source file", Mandatory = true, ValueFromPipeline = true, ParameterSetName = FileParameterSet)]
[Parameter(HelpMessage = "Source file", Mandatory = true, ValueFromPipeline = true, ParameterSetName = FileToBlobParameterSet)]
[ValidateNotNull]
public CloudFile SrcFile { get; set; }
[Alias("SrcUri", "SourceUri")]
[Parameter(HelpMessage = "Source blob uri", Mandatory = true,
ValueFromPipelineByPropertyName = true, ParameterSetName = UriParameterSet)]
public string AbsoluteUri { get; set; }
[Alias("DestinationContainer")]
[Parameter(HelpMessage = "Destination container name", Mandatory = true, ParameterSetName = ContainerNameParameterSet)]
[Parameter(HelpMessage = "Destination container name", Mandatory = true, ParameterSetName = UriParameterSet)]
[Parameter(HelpMessage = "Destination container name", Mandatory = true, ParameterSetName = BlobParameterSet)]
[Parameter(HelpMessage = "Destination container name", Mandatory = true, ParameterSetName = ContainerParameterSet)]
[Parameter(HelpMessage = "Destination container name", Mandatory = true, ParameterSetName = ShareNameParameterSet)]
[Parameter(HelpMessage = "Destination container name", Mandatory = true, ParameterSetName = ShareParameterSet)]
[Parameter(HelpMessage = "Destination container name", Mandatory = true, ParameterSetName = DirParameterSet)]
[Parameter(HelpMessage = "Destination container name", Mandatory = true, ParameterSetName = FileParameterSet)]
public string DestContainer { get; set; }
[Alias("DestinationBlob")]
[Parameter(HelpMessage = "Destination blob name", Mandatory = true, ParameterSetName = UriParameterSet)]
[Parameter(HelpMessage = "Destination blob name", Mandatory = false, ParameterSetName = ContainerNameParameterSet)]
[Parameter(HelpMessage = "Destination blob name", Mandatory = false, ParameterSetName = BlobParameterSet)]
[Parameter(HelpMessage = "Destination blob name", Mandatory = false, ParameterSetName = ContainerParameterSet)]
[Parameter(HelpMessage = "Destination blob name", Mandatory = false, ParameterSetName = ShareNameParameterSet)]
[Parameter(HelpMessage = "Destination blob name", Mandatory = false, ParameterSetName = ShareParameterSet)]
[Parameter(HelpMessage = "Destination blob name", Mandatory = false, ParameterSetName = DirParameterSet)]
[Parameter(HelpMessage = "Destination blob name", Mandatory = false, ParameterSetName = FileParameterSet)]
public string DestBlob { get; set; }
[Alias("DestICloudBlob", "DestinationCloudBlob", "DestinationICloudBlob")]
[Parameter(HelpMessage = "Destination CloudBlob object", Mandatory = true, ParameterSetName = BlobToBlobParameterSet)]
[Parameter(HelpMessage = "Destination CloudBlob object", Mandatory = true, ParameterSetName = FileToBlobParameterSet)]
public CloudBlob DestCloudBlob { get; set; }
[Parameter(HelpMessage = "Premium Page Blob Tier", Mandatory = false, ParameterSetName = ContainerNameParameterSet)]
[Parameter(HelpMessage = "Premium Page Blob Tier", Mandatory = false, ParameterSetName = BlobParameterSet)]
[Parameter(HelpMessage = "Premium Page Blob Tier", Mandatory = false, ParameterSetName = BlobToBlobParameterSet)]
[Parameter(HelpMessage = "Premium Page Blob Tier", Mandatory = false, ParameterSetName = ContainerParameterSet)]
public PremiumPageBlobTier PremiumPageBlobTier
{
get
{
return pageBlobTier.Value;
}
set
{
pageBlobTier = value;
}
}
private PremiumPageBlobTier? pageBlobTier = null;
[Alias("SrcContext", "SourceContext")]
[Parameter(HelpMessage = "Source Azure Storage Context Object", ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = ContainerNameParameterSet)]
[Parameter(HelpMessage = "Source Azure Storage Context Object", ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = BlobParameterSet)]
[Parameter(HelpMessage = "Source Azure Storage Context Object", ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = BlobToBlobParameterSet)]
[Parameter(HelpMessage = "Source Azure Storage Context Object", ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = ContainerParameterSet)]
[Parameter(HelpMessage = "Source Azure Storage Context Object", ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = ShareNameParameterSet)]
[Parameter(HelpMessage = "Source Azure Storage Context Object", ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = ShareParameterSet)]
[Parameter(HelpMessage = "Source Azure Storage Context Object", ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = DirParameterSet)]
[Parameter(HelpMessage = "Source Azure Storage Context Object", ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = FileParameterSet)]
[Parameter(HelpMessage = "Source Azure Storage Context Object", ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = FileToBlobParameterSet)]
[Parameter(HelpMessage = "Source Azure Storage Context Object", ParameterSetName = UriParameterSet)]
public override IStorageContext Context { get; set; }
[Alias("DestinationContext")]
[Parameter(HelpMessage = "Destination Storage context object", Mandatory = false)]
public IStorageContext DestContext { get; set; }
private bool skipSourceChannelInit;
/// <summary>
/// Create blob client and storage service management channel if need to.
/// </summary>
/// <returns>IStorageManagement object</returns>
protected override IStorageBlobManagement CreateChannel()
{
//Init storage blob management channel
if (skipSourceChannelInit)
{
return null;
}
else
{
return base.CreateChannel();
}
}
/// <summary>
/// Begin cmdlet processing
/// </summary>
protected override void BeginProcessing()
{
if (ParameterSetName == UriParameterSet)
{
skipSourceChannelInit = true;
}
base.BeginProcessing();
}
private IStorageFileManagement GetFileChannel()
{
return new StorageFileManagement(GetCmdletStorageContext());
}
/// <summary>
/// Set up the Channel object for Destination container and blob
/// </summary>
internal IStorageBlobManagement GetDestinationChannel()
{
//If destChannel exits, reuse it.
//If desContext exits, use it.
//If Channl object exists, use it.
//Otherwise, create a new channel.
IStorageBlobManagement destChannel = default(IStorageBlobManagement);
if (destChannel == null)
{
if (DestContext == null)
{
if (Channel != null)
{
destChannel = Channel;
}
else
{
destChannel = base.CreateChannel();
}
}
else
{
destChannel = CreateChannel(this.GetCmdletStorageContext(DestContext));
}
}
return destChannel;
}
/// <summary>
/// Execute command
/// </summary>
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
public override void ExecuteCmdlet()
{
IStorageBlobManagement destChannel = GetDestinationChannel();
IStorageBlobManagement srcChannel = Channel;
string target = string.Empty;
Action copyAction = null;
switch (ParameterSetName)
{
case ContainerNameParameterSet:
copyAction = () => StartCopyBlob(srcChannel, destChannel, SrcContainer, SrcBlob, DestContainer, DestBlob);
target = SrcBlob;
break;
case UriParameterSet:
copyAction = () => StartCopyBlob(destChannel, AbsoluteUri, DestContainer, DestBlob, (Context != null? GetCmdletStorageContext(Context) : null));
target = AbsoluteUri;
break;
case BlobParameterSet:
copyAction = () => StartCopyBlob(destChannel, CloudBlob, DestContainer, DestBlob);
target = CloudBlob.Name;
break;
case ContainerParameterSet:
copyAction = () => StartCopyBlob(srcChannel, destChannel, CloudBlobContainer.Name, SrcBlob, DestContainer, DestBlob);
target = SrcBlob;
break;
case BlobToBlobParameterSet:
copyAction = () => StartCopyBlob(destChannel, CloudBlob, DestCloudBlob);
target = CloudBlob.Name;
break;
case ShareNameParameterSet:
copyAction = () => StartCopyFromFile(
this.GetFileChannel(),
destChannel,
this.SrcShareName,
this.SrcFilePath,
this.DestContainer,
this.DestBlob);
target = SrcFilePath;
break;
case ShareParameterSet:
copyAction = () => StartCopyFromFile(
destChannel,
this.SrcShare.GetRootDirectoryReference(),
this.SrcFilePath,
this.DestContainer,
this.DestBlob);
target = SrcFilePath;
break;
case DirParameterSet:
copyAction = () => StartCopyFromFile(
destChannel,
this.SrcDir,
this.SrcFilePath,
this.DestContainer,
this.DestBlob);
target = SrcFilePath;
break;
case FileParameterSet:
copyAction = () => StartCopyFromFile(
destChannel,
this.SrcFile,
this.DestContainer,
this.DestBlob);
target = SrcFile.Name;
break;
case FileToBlobParameterSet:
copyAction = () => StartCopyFromFile(
destChannel,
this.SrcFile,
this.DestCloudBlob);
target = SrcFile.Name;
break;
}
if (copyAction != null && ShouldProcess(target, VerbsCommon.Copy))
{
copyAction();
}
}
/// <summary>
/// Start copy operation by source and destination CloudBlob object
/// </summary>
/// <param name="srcCloudBlob">Source CloudBlob object</param>
/// <param name="destCloudBlob">Destination CloudBlob object</param>
/// <returns>Destination CloudBlob object</returns>
private void StartCopyBlob(IStorageBlobManagement destChannel, CloudBlob srcCloudBlob, CloudBlob destCloudBlob)
{
ValidateBlobType(srcCloudBlob);
ValidateBlobTier(srcCloudBlob.BlobType, pageBlobTier);
Func<long, Task> taskGenerator = (taskId) => StartCopyAsync(taskId, destChannel, srcCloudBlob, destCloudBlob);
RunTask(taskGenerator);
}
/// <summary>
/// Start copy operation by source CloudBlob object
/// </summary>
/// <param name="srcCloudBlob">Source CloudBlob object</param>
/// <param name="destContainer">Destinaion container name</param>
/// <param name="destBlobName">Destination blob name</param>
/// <returns>Destination CloudBlob object</returns>
private void StartCopyBlob(IStorageBlobManagement destChannel, CloudBlob srcCloudBlob, string destContainer, string destBlobName)
{
if (string.IsNullOrEmpty(destBlobName))
{
destBlobName = srcCloudBlob.Name;
}
CloudBlob destBlob = this.GetDestBlob(destChannel, destContainer, destBlobName, srcCloudBlob.BlobType);
this.StartCopyBlob(destChannel, srcCloudBlob, destBlob);
}
/// <summary>
/// Start copy operation by source uri
/// </summary>
/// <param name="srcCloudBlob">Source uri</param>
/// <param name="destContainer">Destinaion container name</param>
/// <param name="destBlobName">Destination blob name</param>
/// <returns>Destination CloudBlob object</returns>
private void StartCopyBlob(IStorageBlobManagement destChannel, string srcUri, string destContainer, string destBlobName, AzureStorageContext context)
{
if (context != null)
{
Uri sourceUri = new Uri(srcUri);
Uri contextUri = new Uri(context.BlobEndPoint);
if (sourceUri.Host.ToLower() == contextUri.Host.ToLower())
{
CloudBlobClient blobClient = context.StorageAccount.CreateCloudBlobClient();
CloudBlob blobReference = null;
try
{
blobReference = Util.GetBlobReferenceFromServer(blobClient, sourceUri);
}
catch (InvalidOperationException)
{
blobReference = null;
}
if (null == blobReference)
{
throw new ResourceNotFoundException(String.Format(ResourceV1.BlobUriNotFound, sourceUri.ToString()));
}
StartCopyBlob(destChannel, blobReference, destContainer, destBlobName);
}
else
{
WriteWarning(String.Format(ResourceV1.StartCopySourceContextMismatch, srcUri, context.BlobEndPoint));
}
}
else
{
CloudBlobContainer container = destChannel.GetContainerReference(destContainer);
Func<long, Task> taskGenerator = (taskId) => StartCopyAsync(taskId, destChannel, new Uri(srcUri), container, destBlobName);
RunTask(taskGenerator);
}
}
/// <summary>
/// Start copy operation by container name and blob name
/// </summary>
/// <param name="srcContainerName">Source container name</param>
/// <param name="srcBlobName">Source blob name</param>
/// <param name="destContainer">Destinaion container name</param>
/// <param name="destBlobName">Destination blob name</param>
/// <returns>Destination CloudBlob object</returns>
private void StartCopyBlob(IStorageBlobManagement SrcChannel, IStorageBlobManagement destChannel, string srcContainerName, string srcBlobName, string destContainerName, string destBlobName)
{
NameUtil.ValidateBlobName(srcBlobName);
NameUtil.ValidateContainerName(srcContainerName);
if (string.IsNullOrEmpty(destBlobName))
{
destBlobName = srcBlobName;
}
AccessCondition accessCondition = null;
BlobRequestOptions options = RequestOptions;
CloudBlobContainer container = SrcChannel.GetContainerReference(srcContainerName);
CloudBlob blob = GetBlobReferenceFromServerWithContainer(SrcChannel, container, srcBlobName, accessCondition, options, OperationContext);
this.StartCopyBlob(destChannel, blob, destContainerName, destBlobName);
}
private void StartCopyFromFile(IStorageFileManagement srcChannel, IStorageBlobManagement destChannel, string srcShareName, string srcFilePath, string destContainerName, string destBlobName)
{
NamingUtil.ValidateShareName(srcShareName, false);
CloudFileShare share = srcChannel.GetShareReference(srcShareName);
this.StartCopyFromFile(destChannel, share.GetRootDirectoryReference(), srcFilePath, destContainerName, destBlobName);
}
private void StartCopyFromFile(IStorageBlobManagement destChannel, CloudFileDirectory srcDir, string srcFilePath, string destContainerName, string destBlobName)
{
string[] path = NamingUtil.ValidatePath(srcFilePath, true);
CloudFile file = srcDir.GetFileReferenceByPath(path);
this.StartCopyFromFile(destChannel, file, destContainerName, destBlobName);
}
private void StartCopyFromFile(IStorageBlobManagement destChannel, CloudFile srcFile, string destContainerName, string destBlobName)
{
if (string.IsNullOrEmpty(destBlobName))
{
destBlobName = srcFile.GetFullPath();
}
CloudBlob destBlob = this.GetDestBlob(destChannel, destContainerName, destBlobName, BlobType.BlockBlob);
this.StartCopyFromFile(destChannel, srcFile, destBlob);
}
private void StartCopyFromFile(IStorageBlobManagement destChannel, CloudFile srcFile, CloudBlob destBlob)
{
CloudBlockBlob destBlockBlob = destBlob as CloudBlockBlob;
if (null == destBlockBlob)
{
throw new InvalidOperationException(ResourceV1.OnlyCopyFromBlockBlobToAzureFile);
}
Func<long, Task> taskGenerator = (taskId) => this.StartCopyFromFile(taskId, destChannel, srcFile, destBlockBlob); ;
RunTask(taskGenerator);
}
private async Task StartCopyFromBlob(long taskId, IStorageBlobManagement destChannel, CloudBlob srcBlob, CloudBlob destBlob)
{
try
{
await StartCopyFromUri(taskId, destChannel, srcBlob.GenerateUriWithCredentials(), destBlob).ConfigureAwait(false);
}
catch (StorageException ex)
{
if (0 == string.Compare(ex.Message, BlobTypeMismatch, StringComparison.OrdinalIgnoreCase))
{
// Current use error message to decide whether it caused by blob type mismatch,
// We should ask xscl to expose an error code for this..
// Opened workitem 1487579 to track this.
throw new InvalidOperationException(ResourceV1.DestinationBlobTypeNotMatch);
}
else
{
throw;
}
}
}
private async Task StartCopyFromUri(long taskId, IStorageBlobManagement destChannel, Uri srcUri, CloudBlob destBlob)
{
bool destExist = true;
try
{
await destBlob.FetchAttributesAsync(null, this.RequestOptions, this.OperationContext, this.CmdletCancellationToken).ConfigureAwait(false);
}
catch (StorageException ex)
{
if (ex.IsNotFoundException())
{
destExist = false;
}
else
{
throw;
}
}
if (!destExist || this.ConfirmOverwrite(srcUri.AbsoluteUri.ToString(), destBlob.Uri.ToString()))
{
string copyId;
//Clean the Metadata of the destination Blob object, or the source metadata won't overwirte the dest blob metadata. See https://docs.microsoft.com/en-us/rest/api/storageservices/copy-blob
destBlob.Metadata.Clear();
if (pageBlobTier == null)
{
copyId = await destChannel.StartCopyAsync(destBlob, srcUri, null, null, this.RequestOptions, this.OperationContext, this.CmdletCancellationToken).ConfigureAwait(false);
}
else
{
copyId = await destChannel.StartCopyAsync((CloudPageBlob)destBlob, srcUri, pageBlobTier.Value, null, null, this.RequestOptions, this.OperationContext, this.CmdletCancellationToken).ConfigureAwait(false);
}
this.OutputStream.WriteVerbose(taskId, String.Format(ResourceV1.CopyDestinationBlobPending, destBlob.Name, destBlob.Container.Name, copyId));
this.WriteCloudBlobObject(taskId, destChannel, destBlob);
}
}
private async Task StartCopyFromFile(long taskId, IStorageBlobManagement destChannel, CloudFile srcFile, CloudBlockBlob destBlob)
{
await this.StartCopyFromUri(taskId, destChannel, srcFile.GenerateUriWithCredentials(), destBlob).ConfigureAwait(false);
}
private CloudBlob GetDestBlob(IStorageBlobManagement destChannel, string destContainerName, string destBlobName, BlobType blobType)
{
NameUtil.ValidateContainerName(destContainerName);
NameUtil.ValidateBlobName(destBlobName);
CloudBlobContainer container = destChannel.GetContainerReference(destContainerName);
CloudBlob destBlob = null;
if (BlobType.PageBlob == blobType)
{
destBlob = container.GetPageBlobReference(destBlobName);
}
else if (BlobType.BlockBlob == blobType)
{
destBlob = container.GetBlockBlobReference(destBlobName);
}
else if (BlobType.AppendBlob == blobType)
{
destBlob = container.GetAppendBlobReference(destBlobName);
}
else
{
throw new ArgumentException(String.Format(ResourceV1.InvalidBlobType, blobType, destBlobName));
}
return destBlob;
}
/// <summary>
/// Start copy using transfer mangager by source CloudBlob object
/// </summary>
/// <param name="blob">Source CloudBlob object</param>
/// <param name="destContainer">Destination CloudBlobContainer object</param>
/// <param name="destBlobName">Destination blob name</param>
/// <returns>Destination CloudBlob object</returns>
private async Task StartCopyAsync(long taskId, IStorageBlobManagement destChannel, CloudBlob sourceBlob, CloudBlob destBlob)
{
NameUtil.ValidateBlobName(sourceBlob.Name);
NameUtil.ValidateContainerName(destBlob.Container.Name);
NameUtil.ValidateBlobName(destBlob.Name);
await this.StartCopyFromBlob(taskId, destChannel, sourceBlob, destBlob).ConfigureAwait(false);
}
/// <summary>
/// Start copy using transfer mangager by source uri
/// </summary>
/// <param name="uri">source uri</param>
/// <param name="destContainer">Destination CloudBlobContainer object</param>
/// <param name="destBlobName">Destination blob name</param>
/// <returns>Destination CloudBlob object</returns>
private async Task StartCopyAsync(long taskId, IStorageBlobManagement destChannel, Uri uri, CloudBlobContainer destContainer, string destBlobName)
{
NameUtil.ValidateContainerName(destContainer.Name);
NameUtil.ValidateBlobName(destBlobName);
CloudBlob sourceBlob = new CloudBlob(uri);
BlobType destBlobType = BlobType.BlockBlob;
try
{
await sourceBlob.FetchAttributesAsync(null, this.RequestOptions, this.OperationContext, this.CmdletCancellationToken);
//When the source Uri is a file Uri, will get BlobType.Unspecified, and should use block blob in destination
if (sourceBlob.BlobType != BlobType.Unspecified)
destBlobType = sourceBlob.BlobType;
}
catch (StorageException)
{
//use block blob by default
destBlobType = BlobType.BlockBlob;
}
CloudBlob destBlob = GetDestBlob(destChannel, destContainer.Name, destBlobName, destBlobType);
await this.StartCopyFromUri(taskId, destChannel, uri, destBlob);
}
/// <summary>
/// Get DestinationBlob with specified copy id
/// </summary>
/// <param name="container">CloudBlobContainer object</param>
/// <param name="blobName">Blob name</param>
/// <param name="copyId">Current CopyId</param>
/// <returns>Destination CloudBlob object</returns>
private CloudBlob GetDestinationBlobWithCopyId(IStorageBlobManagement destChannel, CloudBlobContainer container, string blobName)
{
AccessCondition accessCondition = null;
BlobRequestOptions options = RequestOptions;
CloudBlob blob = destChannel.GetBlobReferenceFromServer(container, blobName, accessCondition, options, OperationContext);
return blob;
}
public void OnImport()
{
try
{
PowerShell invoker = null;
invoker = PowerShell.Create(RunspaceMode.CurrentRunspace);
invoker.AddScript(File.ReadAllText(FileUtilities.GetContentFilePath(
Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
"AzureStorageStartup.ps1")));
invoker.Invoke();
}
catch
{
// Ignore exception.
}
}
}
}
| 48.35755 | 233 | 0.609597 | [
"MIT"
] | bganapa/azure-powershell | src/Storage/custom/Dataplane.v1/Blob/Cmdlet/StartAzureStorageBlobCopy.cs | 33,248 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Intense
{
/// <summary>
/// Defines a uniform contract for hierarchical data structures.
/// </summary>
public interface IHierarchyService<T>
{
/// <summary>
/// Retrieves the children of specified object.
/// </summary>
/// <param name="o"></param>
/// <returns></returns>
IEnumerable<T> GetChildren(T o);
/// <summary>
/// Retrieves the parent of specified object.
/// </summary>
/// <param name="o"></param>
/// <returns></returns>
T GetParent(T o);
}
}
| 26.142857 | 69 | 0.553279 | [
"MIT"
] | mediaexplorer74/InteropTools | UI/Libs/Intense/IHierarchyService.cs | 707 | C# |
using System.Collections.Generic;
using System.Linq;
using Terraria;
using Terraria.ID;
using Terraria.ModLoader;
using Terraria.ModLoader.IO;
namespace ICantBelieveItsNotVanilla.Items.Accessories
{
public class TheArtOfWar : MetaItem
{
public static string ToolTipTemplate = ModHelper.Tooltip(
"''Knowing the enemy enables you to take",
"the offensive, knowing yourself enables",
"you to stand on the defensive.''",
"- Sun Tzu, The Art of War",
"",
"Enemies understood: {0}"
);
public Dictionary<int, bool> NpcBuffs = new Dictionary<int, bool>();
public override void SetDefaults()
{
item.name = "The Art of War";
item.width = 32;
item.height = 28;
item.maxStack = 1;
item.value = Item.buyPrice(0, 0, 75, 0);
item.accessory = true;
item.rare = 3;
}
public override void UpdateAccessory(Player player, bool hideVisual)
{
if(player != null && player.inventory.Length > 0)
{
// Consume Banners
Item item = null;
int[] npcids = null;
for (int i = 0; i < player.inventory.Length; i++)
{
item = player.inventory[i];
if (item != null && Constants.BANNER_IDS.ContainsKey(item.type))
{
npcids = Constants.BANNER_IDS[item.type];
foreach (int npc in npcids)
NpcBuffs[Item.NPCtoBanner(npc)] = true;
player.inventory[i].TurnToAir();
}
}
}
}
public override TagCompound Save()
{
return new TagCompound
{
{ "npcs", NpcBuffs.Select(x => x.Key).ToArray() }
};
}
public override void Load(TagCompound tag)
{
NpcBuffs = tag.GetTag<int[]>("npcs").ToDictionary(x => x, x => true);
}
public override ModItem Clone(Item item)
{
TheArtOfWar clone = new TheArtOfWar();
clone.sourceItem = sourceItem.Clone();
clone.NpcBuffs = new Dictionary<int, bool>(NpcBuffs);
return clone;
}
public override void ModifyTooltips(List<TooltipLine> tooltips)
{
foreach(TooltipLine line in tooltips)
{
if(line.Name == "Tooltip")
{
line.text = string.Format(ToolTipTemplate, NpcBuffs.Where(x => x.Value).Count());
}
}
}
public override bool Autoload(ref string name, ref string texture, IList<EquipType> equips)
{
//equips.Add(EquipType.Shield);
return true;
}
public override void AddRecipes()
{
RecipeBuilder.CreateFor(mod)
.AddIngredient(ItemID.Book)
.AddTile(ItemID.Bookcase)
.SetResult(this);
}
}
}
| 31.137255 | 101 | 0.499055 | [
"MIT"
] | Malexion/ICantBelieveItsNotVanilla | Items/Accessories/TheArtOfWar.cs | 3,178 | C# |
using System;
using System.Collections.Generic;
using NUnit.Framework;
using Rebus.Bus;
using Rebus.Configuration;
using Rebus.Persistence.InMemory;
using Rebus.Tests.Persistence.Sagas;
using Rhino.Mocks;
using Shouldly;
namespace Rebus.Tests.Unit
{
[TestFixture]
public class TestDispatcher : FixtureBase
{
Dispatcher dispatcher;
HandlerActivatorForTesting activator;
RearrangeHandlersPipelineInspector pipelineInspector;
protected override void DoSetUp()
{
activator = new HandlerActivatorForTesting();
pipelineInspector = new RearrangeHandlersPipelineInspector();
dispatcher = new Dispatcher(new InMemorySagaPersister(),
activator,
new InMemorySubscriptionStorage(),
pipelineInspector,
new DeferredMessageHandlerForTesting(),
null);
}
[Test]
public void ThrowsIfTwoSagaHandlersArePresentInHandlerPipeline()
{
// arrange
activator.UseHandler(new FirstSaga());
activator.UseHandler(new SecondSaga());
var messageThatCanBeHandledByBothSagas = new SomeMessage();
// act
var exception =
Should.Throw<MultipleSagaHandlersFoundException>(
async () => await dispatcher.Dispatch(messageThatCanBeHandledByBothSagas));
// assert
exception.Message.ShouldContain("FirstSaga");
exception.Message.ShouldContain("SecondSaga");
exception.Message.ShouldContain("SomeMessage");
}
[Test]
public void DoesNotThrowIfTwoSagaHandlersArePresentInHandlerPipeline_ButSagaPersisterCanUpdateMultipleSagaDatasAtomically()
{
// arrange
var fakePersister = MockRepository.GenerateMock<IStoreSagaData, ICanUpdateMultipleSagaDatasAtomically>();
dispatcher = new Dispatcher(fakePersister,
activator,
new InMemorySubscriptionStorage(),
pipelineInspector,
new DeferredMessageHandlerForTesting(),
null);
activator.UseHandler(new FirstSaga());
activator.UseHandler(new SecondSaga());
var messageThatCanBeHandledByBothSagas = new SomeMessage();
// act
Assert.DoesNotThrow(() => dispatcher.Dispatch(messageThatCanBeHandledByBothSagas));
}
class FirstSaga : Saga<SomeSagaData>, IHandleMessages<SomeMessage>
{
public override void ConfigureHowToFindSaga()
{
}
public void Handle(SomeMessage message)
{
}
}
class SecondSaga : Saga<SomeSagaData>, IHandleMessages<SomeMessage>
{
public override void ConfigureHowToFindSaga()
{
}
public void Handle(SomeMessage message)
{
}
}
class SomeSagaData : ISagaData
{
public Guid Id { get; set; }
public int Revision { get; set; }
}
[Test]
public void ThrowsIfNoHandlersCanBeFound()
{
// arrange
var theMessage = new SomeMessage();
// act
var ex = Should.Throw<UnhandledMessageException>(async () => await dispatcher.Dispatch(theMessage));
// assert
ex.UnhandledMessage.ShouldBe(theMessage);
}
[Test]
public void PolymorphicDispatchWorksLikeExpected()
{
// arrange
var calls = new List<string>();
activator.UseHandler(new AnotherHandler(calls))
.UseHandler(new YetAnotherHandler(calls))
.UseHandler(new AuthHandler(calls));
pipelineInspector.SetOrder(typeof (AuthHandler), typeof (AnotherHandler));
// act
dispatcher.Dispatch(new SomeMessage());
// assert
calls.Count.ShouldBe(5);
calls[0].ShouldBe("AuthHandler: object");
calls[1].ShouldStartWith("AnotherHandler");
calls[2].ShouldStartWith("AnotherHandler");
calls[3].ShouldStartWith("AnotherHandler");
calls[4].ShouldBe("YetAnotherHandler: another_interface");
}
[Test]
public void NewSagaIsMarkedAsSuch()
{
var saga = new SmallestSagaOnEarthCorrelatedOnInitialMessage();
activator.UseHandler(saga);
dispatcher.Dispatch(new SomeMessageWithANumber(1));
saga.IsNew.ShouldBe(true);
}
[Test]
public void SagaInitiatedTwiceIsNotMarkedAsNewTheSecondTime()
{
var saga = new SmallestSagaOnEarthCorrelatedOnInitialMessage();
activator.UseHandler(saga);
dispatcher.Dispatch(new SomeMessageWithANumber(1));
dispatcher.Dispatch(new SomeMessageWithANumber(1));
saga.IsNew.ShouldBe(false);
}
interface ISomeInterface
{
}
interface IAnotherInterface
{
}
class SomeMessage : ISomeInterface, IAnotherInterface
{
}
class SomeMessageWithANumber
{
public SomeMessageWithANumber(int theNumber)
{
TheNumber = theNumber;
}
public int TheNumber { get; private set; }
}
class InitiatingMessageWithANumber
{
public InitiatingMessageWithANumber(int theNumber)
{
TheNumber = theNumber;
}
public int TheNumber { get; private set; }
}
class SmallestSagaOnEarthCorrelatedOnInitialMessage : Saga<SagaData>, IAmInitiatedBy<SomeMessageWithANumber>
{
public void Handle(SomeMessageWithANumber message)
{
Data.TheNumber = message.TheNumber;
}
public override void ConfigureHowToFindSaga()
{
Incoming<SomeMessageWithANumber>(m => m.TheNumber).CorrelatesWith(d => d.TheNumber);
}
}
class SmallestSagaOnEarthNotCorrelatedOnInitialMessage : Saga<SagaData>,
IAmInitiatedBy<InitiatingMessageWithANumber>,
IHandleMessages<SomeMessageWithANumber>
{
public int TimesHandlingSomeMessageWithANumber { get; set; }
public void Handle(SomeMessageWithANumber message)
{
TimesHandlingSomeMessageWithANumber++;
}
public void Handle(InitiatingMessageWithANumber message)
{
Data.TheNumber = message.TheNumber;
}
public override void ConfigureHowToFindSaga()
{
Incoming<SomeMessageWithANumber>(m => m.TheNumber).CorrelatesWith(d => d.TheNumber);
}
}
class SagaData : ISagaData
{
public Guid Id { get; set; }
public int Revision { get; set; }
public int TheNumber { get; set; }
}
class AuthHandler : IHandleMessages<object>
{
readonly List<string> calls;
public AuthHandler(List<string> calls)
{
this.calls = calls;
}
public void Handle(object message)
{
calls.Add("AuthHandler: object");
}
}
class AnotherHandler : IHandleMessages<ISomeInterface>, IHandleMessages<object>,
IHandleMessages<IAnotherInterface>
{
readonly List<string> calls;
public AnotherHandler(List<string> calls)
{
this.calls = calls;
}
public void Handle(ISomeInterface message)
{
calls.Add("AnotherHandler: some_interface");
}
public void Handle(object message)
{
calls.Add("AnotherHandler: object");
}
public void Handle(IAnotherInterface message)
{
calls.Add("AnotherHandler: another_interface");
}
}
class YetAnotherHandler : IHandleMessages<IAnotherInterface>
{
readonly List<string> calls;
public YetAnotherHandler(List<string> calls)
{
this.calls = calls;
}
public void Handle(IAnotherInterface message)
{
calls.Add("YetAnotherHandler: another_interface");
}
}
}
} | 32.571429 | 132 | 0.529953 | [
"Apache-2.0"
] | jacobbonde/Rebus | src/Rebus.Tests/Unit/TestDispatcher.cs | 9,350 | C# |
{{- SKIP_GENERATE = DtoInfo.CreateTypeName == DtoInfo.UpdateTypeName -}}
using System;
using System.ComponentModel;
{{~ for prop in EntityInfo.Properties ~}}
{{~ if prop | abp.is_ignore_property; continue; end ~}}
{{~ if prop.Type | string.starts_with "IEnumerable<" ~}}
using System.Collections.Generic;
{{~ end ~}}
{{~ if !for.last ~}}
{{~ end ~}}
{{~ end ~}}
namespace {{ EntityInfo.Namespace }}.Dtos
{
[Serializable]
public class {{ DtoInfo.UpdateTypeName }}
{
{{~ for prop in EntityInfo.Properties ~}}
{{~ if prop | abp.is_ignore_property; continue; end ~}}
{{~ if !Option.SkipLocalization && Option.SkipViewModel ~}}
[DisplayName("{{ EntityInfo.Name + prop.Name}}")]
{{~ end ~}}
{{~ if prop.Type | string.starts_with "IEnumerable<" ~}}
public {{ prop.Type | string.replace ">" "Dto>"}} {{ prop.Name }}Dto { get; set; }
{{~ else ~}}
public {{ prop.Type }} {{ prop.Name }} { get; set; }
{{~ end ~}}
{{~ if !for.last ~}}
{{~ end ~}}
{{~ end ~}}
}
} | 32.176471 | 90 | 0.548446 | [
"MIT"
] | blyzer/AbpHelper.CLI | src/AbpHelper.Core/Templates/Crud/Groups/Service/src/{{ProjectInfo.FullName}}.Application.Contracts/{{EntityInfo.RelativeDirectory}}/Dtos/{{DtoInfo.UpdateTypeName}}.cs | 1,094 | C# |
using System.Threading.Tasks;
using CatFactory.EntityFrameworkCore;
using CatFactory.ObjectRelationalMapping.Actions;
using CatFactory.SqlServer;
using Xunit;
namespace CatFactory.AspNetCore.Tests
{
public class ScaffoldingTests
{
[Fact]
public async Task ScaffoldingAPIFromOnlineStoreDatabaseAsync()
{
// Import database
var database = await SqlServerDatabaseFactory
.ImportAsync("server=(local);database=OnlineStore;integrated security=yes;", "dbo.sysdiagrams");
// Create instance of Entity Framework Core Project
var entityFrameworkProject = EntityFrameworkCoreProject
.CreateForV2x("OnlineStore.Domain", database, @"C:\Temp\CatFactory.AspNetCore\OnlineStore.Domain");
// Apply settings for project
entityFrameworkProject.GlobalSelection(settings =>
{
settings.ForceOverwrite = true;
settings.ConcurrencyToken = "Timestamp";
settings.AuditEntity = new AuditEntity
{
CreationUserColumnName = "CreationUser",
CreationDateTimeColumnName = "CreationDateTime",
LastUpdateUserColumnName = "LastUpdateUser",
LastUpdateDateTimeColumnName = "LastUpdateDateTime"
};
});
entityFrameworkProject.Selection("Sales.OrderHeader", settings => settings.EntitiesWithDataContracts = true);
// Build features for project, group all entities by schema into a feature
entityFrameworkProject.BuildFeatures();
// Scaffolding =^^=
entityFrameworkProject
.ScaffoldDomain()
;
var aspNetCoreProject = entityFrameworkProject
.CreateAspNetCore2xProject("OnlineStore.API", @"C:\Temp\CatFactory.AspNetCore\OnlineStore.API");
aspNetCoreProject.GlobalSelection(settings => settings.ForceOverwrite = true);
aspNetCoreProject.Selection("Sales.OrderDetail", settings =>
{
settings
.RemoveAction<ReadAllAction>()
.RemoveAction<ReadByKeyAction>()
.RemoveAction<AddEntityAction>()
.RemoveAction<UpdateEntityAction>()
.RemoveAction<RemoveEntityAction>();
});
aspNetCoreProject.ScaffoldAspNetCore();
}
//[Fact]
//public async Task ScaffoldingWebAPIFromOnlineStoreDatabaseAsync()
//{
// // Import database
// var database = await SqlServerDatabaseFactory
// .ImportAsync("server=(local);database=OnlineStore;integrated security=yes;", "dbo.sysdiagrams");
// // Create instance of Entity Framework Core Project
// var entityFrameworkProject = EntityFrameworkCoreProject
// .CreateForV2x("OnlineStore.Core", database, @"C:\Temp\CatFactory.AspNetCore\OnlineStore.Core");
// // Apply settings for project
// entityFrameworkProject.GlobalSelection(settings =>
// {
// settings.ForceOverwrite = true;
// settings.ConcurrencyToken = "Timestamp";
// settings.AuditEntity = new AuditEntity
// {
// CreationUserColumnName = "CreationUser",
// CreationDateTimeColumnName = "CreationDateTime",
// LastUpdateUserColumnName = "LastUpdateUser",
// LastUpdateDateTimeColumnName = "LastUpdateDateTime"
// };
// });
// entityFrameworkProject.Selection("Sales.OrderHeader", settings => settings.EntitiesWithDataContracts = true);
// // Build features for project, group all entities by schema into a feature
// entityFrameworkProject.BuildFeatures();
// // Scaffolding =^^=
// entityFrameworkProject
// .ScaffoldEntityLayer()
// .ScaffoldDataLayer();
// var aspNetCoreProject = entityFrameworkProject
// .CreateAspNetCore2xProject("OnlineStore.WebAPI", @"C:\Temp\CatFactory.AspNetCore\OnlineStore.WebAPI");
// aspNetCoreProject.GlobalSelection(settings => settings.ForceOverwrite = true);
// aspNetCoreProject.Selection("Sales.OrderDetail", settings =>
// {
// settings
// .RemoveAction<ReadAllAction>()
// .RemoveAction<ReadByKeyAction>()
// .RemoveAction<AddEntityAction>()
// .RemoveAction<UpdateEntityAction>()
// .RemoveAction<RemoveEntityAction>();
// });
// aspNetCoreProject.ScaffoldAspNetCore();
//}
//[Fact]
//public async Task ScaffoldingAPIWithFluentValidationFromOnlineStoreDatabaseAsync()
//{
// // Import database
// var database = await SqlServerDatabaseFactory
// .ImportAsync("server=(local);database=OnlineStore;integrated security=yes;", "dbo.sysdiagrams");
// // Create instance of Entity Framework Core Project
// var entityFrameworkProject = EntityFrameworkCoreProject
// .CreateForV2x("OnlineStore.Core", database, @"C:\Temp\CatFactory.AspNetCore\OnlineStore.Core");
// // Apply settings for project
// entityFrameworkProject.GlobalSelection(settings =>
// {
// settings.ForceOverwrite = true;
// settings.ConcurrencyToken = "Timestamp";
// settings.AuditEntity = new AuditEntity
// {
// CreationUserColumnName = "CreationUser",
// CreationDateTimeColumnName = "CreationDateTime",
// LastUpdateUserColumnName = "LastUpdateUser",
// LastUpdateDateTimeColumnName = "LastUpdateDateTime"
// };
// });
// entityFrameworkProject.Selection("Sales.OrderHeader", settings => settings.EntitiesWithDataContracts = true);
// // Build features for project, group all entities by schema into a feature
// entityFrameworkProject.BuildFeatures();
// // Scaffolding =^^=
// entityFrameworkProject
// .ScaffoldEntityLayer()
// .ScaffoldDataLayer()
// ;
// var aspNetCoreProject = entityFrameworkProject
// .CreateAspNetCore2xProject("OnlineStoreWithFluentValidation.WebAPI", @"C:\Temp\CatFactory.AspNetCore\OnlineStoreWithFluentValidation.WebAPI");
// aspNetCoreProject.GlobalSelection(settings =>
// {
// settings.ForceOverwrite = true;
// settings.UseDataAnnotationsToValidateRequestModels = false;
// });
// aspNetCoreProject.Selection("Sales.OrderDetail", settings =>
// {
// settings
// .RemoveAction<ReadAllAction>()
// .RemoveAction<ReadByKeyAction>()
// .RemoveAction<AddEntityAction>()
// .RemoveAction<UpdateEntityAction>()
// .RemoveAction<RemoveEntityAction>();
// });
// aspNetCoreProject
// .ScaffoldFluentValidation()
// .ScaffoldAspNetCore()
// ;
//}
//[Fact]
//public async Task ScaffoldingAPIFromNorthwindDatabaseAsync()
//{
// // Import database
// var database = await SqlServerDatabaseFactory
// .ImportAsync("server=(local);database=Northwind;integrated security=yes;", "dbo.sysdiagrams");
// // Create instance of Entity Framework Core Project
// var entityFrameworkProject = EntityFrameworkCoreProject
// .CreateForV2x("Northwind.Core", database, @"C:\Temp\CatFactory.AspNetCore\Northwind.Core");
// // Apply settings for project
// entityFrameworkProject.GlobalSelection(settings =>
// {
// settings.ForceOverwrite = true;
// settings.ConcurrencyToken = "Timestamp";
// settings.AuditEntity = new AuditEntity
// {
// CreationUserColumnName = "CreationUser",
// CreationDateTimeColumnName = "CreationDateTime",
// LastUpdateUserColumnName = "LastUpdateUser",
// LastUpdateDateTimeColumnName = "LastUpdateDateTime"
// };
// });
// entityFrameworkProject.Selection("dbo.Orders", settings => settings.EntitiesWithDataContracts = true);
// // Build features for project, group all entities by schema into a feature
// entityFrameworkProject.BuildFeatures();
// // Scaffolding =^^=
// entityFrameworkProject
// .ScaffoldEntityLayer()
// .ScaffoldDataLayer()
// ;
// var aspNetCoreProject = entityFrameworkProject
// .CreateAspNetCore2xProject("Northwind.WebAPI", @"C:\Temp\CatFactory.AspNetCore\Northwind.WebAPI");
// aspNetCoreProject.GlobalSelection(settings => settings.ForceOverwrite = true);
// aspNetCoreProject.ScaffoldAspNetCore();
//}
}
}
| 42.587444 | 160 | 0.5825 | [
"MIT"
] | hherzl/CatFactory.AspNetCore | CatFactory.AspNetCore.Tests/ScaffoldingTests.cs | 9,499 | C# |
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using Algebraic.Numbers.Integers;
// ReSharper disable once CheckNamespace
namespace Algebraic.Numbers
{
public static partial class IntegerSequence
{
private static class A000007
{
[Pure]
public static BigInteger GetElement(BigInteger idx)
{
return idx.IsZero ? 1 : 0;
}
[Pure]
public static IEnumerable<BigInteger> Sequence()
{
yield return 1;
while (true)
{
yield return 0;
}
// ReSharper disable once IteratorNeverReturns
}
}
}
} | 25.133333 | 63 | 0.525199 | [
"MIT"
] | RSCorporation/Algebraic | Algebraic/src/Numbers/Integers/Sequences/A000007.cs | 756 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Microsoft.ClearScript;
using Microsoft.ClearScript.V8;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
namespace Handlebars
{
public sealed class ClearScriptBridgeFunctions
{
private readonly ScriptEngine _engine;
private readonly IHandlebarsResourceProvider _resourceProvider;
public ClearScriptBridgeFunctions(ScriptEngine engine,
IHandlebarsResourceProvider resourceProvider)
{
_engine = engine;
_resourceProvider = resourceProvider;
}
public void require(string url)
{
var resource = _resourceProvider.GetScript(url);
_engine.Execute(resource);
}
}
public sealed class ClearScriptEngine : IHandlebarsEngine
{
#region // Constructor //
public ClearScriptEngine(IHandlebarsResourceProvider resourceProvider)
{
Console.Out.WriteLine("ClearScriptEngine Loaded");
_resourceProvider = resourceProvider;
_context = new V8ScriptEngine();
_context.AddHostObject("clearScriptBridge",
HostItemFlags.GlobalMembers,
new ClearScriptBridgeFunctions(_context, _resourceProvider));
// _context.Script.moduleLoader = new ModuleLoader(_context);
// _context.Execute(File.ReadAllText("require.js"));
// _context.Execute(@"require.load = function(context, name, url) { moduleLoader.LoadModuleAsync(context, name, url); };");
_context.Execute("var raw = [];");
_context.Execute("require('./Script/handlebars-1.0.0.js');");
foreach (var script in HandlebarsConfiguration.Instance.Include)
{
_context.Execute("require('./" + script.Source + "');");
}
}
#endregion
#region // Properties //
private readonly IHandlebarsResourceProvider _resourceProvider;
private readonly V8ScriptEngine _context;
#endregion
public void Clear()
{
_context.Execute("Handlebars.templates = []; " +
"Handlebars.partials = []; ");
// a good opportunity to return ram to it's rightful owner
_context.CollectGarbage(true);
}
public void Compile(string name, string template)
{
template = HandlebarsUtilities.ToJavaScriptString(template);
_context.Execute("raw['" + name + "'] = '" + template + "';\n" +
"Handlebars.templates['" + name + "'] = Handlebars.compile('" + template + "');");
}
public bool Exists(string name)
{
return (bool)_context.Evaluate("typeof Handlebars.templates['" + name + "'] == 'function';");
}
public string ExportPrecompile()
{
var exportJS = @"(function() {
var response = '';
var keys = Object.keys(Handlebars.templates);
for (var i = 0; i < keys.length; i++) {
var pre = Handlebars.precompile(raw[keys[i]]);
response += 'Handlebars.templates[\'' + keys[i] + '\'] = Handlebars.template(' + pre.toString() + ');';
}
return response;
})()";
return (string)_context.Evaluate(exportJS);
}
public void ImportPrecompile(string js)
{
_context.Execute(js);
}
public void PartialCompile(string name, string template)
{
template = HandlebarsUtilities.ToJavaScriptString(template);
_context.Execute("raw['" + name + "'] = '" + template + "';\n" +
"Handlebars.registerPartial('" + name + "','" + template + "');");
}
public bool PartialExists(string name)
{
return (bool)_context.Evaluate("typeof Handlebars.partials['" + name + "'] == 'function';");
}
public string Render(string name, object context)
{
var json = context is string ? (string)context : HandlebarsUtilities.ToJson(context);
return (string)_context.Evaluate("Handlebars.templates['" + name + "'](" + json + ");");
}
public string Render(string name, string template, string json)
{
if (string.IsNullOrEmpty(json)) json = "{}";
return (string)_context.Evaluate("Handlebars.compile('" + HandlebarsUtilities.ToJavaScriptString(template) + "')(" + json + ");");
}
public string Render(string name, string template, object context)
{
string json = context is string ? (string)context : HandlebarsUtilities.ToJson(context);
return Render(name, template, json);
}
public void Remove(string name)
{
_context.Execute("delete Handlebars.templates['" + name + "'];");
}
public void Dispose()
{
_context.Dispose();
}
}
}
| 37.506579 | 157 | 0.525522 | [
"Apache-2.0"
] | james-andrewsmith/handlebars-net | src/Engine/ClearScriptEngine/ClearScriptEngine.cs | 5,703 | C# |
using System;
namespace SampleWebApp.Models
{
public class ErrorViewModel
{
public string RequestId { get; set; }
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
}
}
| 18.5 | 71 | 0.635135 | [
"MIT"
] | kevinhillinger/azureadb2c-aspnetcore-sample | app/backend/SampleWebApp/Models/ErrorViewModel.cs | 222 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
//todo - save where stopped
//todo - add a game menu
namespace SnakeGame
{
class Snake
{
private static string snakeSign = "*";
private static string foodSign = "@";
private static int bodyLength = 5;
private static int sleepTime = 200;
private static int currentDirection = 0;
private static string scoreOutputFileName = "Scores.txt";
private static Dictionary<string, int> scores = new Dictionary<string, int>();
private static Queue<Position> snakeElements = new Queue<Position>();
private static Position food = new Position();
private static Random randomNumberGenerator = new Random();
public struct Position
{
public int X;
public int Y;
public Position(int x, int y)
{
this.X = x;
this.Y = y;
}
};
public static Position[] directionOffsets = new Position[]
{
new Position(1, 0), // right
new Position(-1, 0), // left
new Position (0, 1), // down
new Position(0, -1) //top
};
public static List<string> directionHead = new List<string>
{
">", "<", "v", "^"
};
public static void InitGame()
{
Console.BufferHeight = Console.WindowHeight;
for (int x = 0; x < bodyLength; x++)
{
Position pos = new Position(x, 0);
snakeElements.Enqueue(pos);
}
}
public static void CheckForDirectionChange()
{
//int currentDirection = 0;
ConsoleKeyInfo userInput = Console.ReadKey();
switch (userInput.Key)
{
case ConsoleKey.LeftArrow:
if(currentDirection != 0)
{
currentDirection = 1;
};
break;
case ConsoleKey.UpArrow:
if (currentDirection != 2)
{
currentDirection = 3;
};
break;
case ConsoleKey.DownArrow:
if (currentDirection != 3)
{
currentDirection = 2;
};
break;
case ConsoleKey.RightArrow:
if (currentDirection != 1)
{
currentDirection = 0;
};
break;
case ConsoleKey.Escape:
Environment.Exit(0); break;
}
// return currentDirection;
}
private static int CalculatePoints()
{
int points = (snakeElements.Count - bodyLength) * 100;
return Math.Max(points, 0);
}
private static void EndGame()
{
ReadScores();
Console.Clear();
Console.SetCursorPosition(0, 0);
Console.WriteLine("Game over!");
int points = CalculatePoints();
Console.WriteLine("Your points are: {0}", points);
SaveScore();
PrintScores();
}
private static void ReadScores()
{
if (File.Exists(scoreOutputFileName))
{
var lines = File
.ReadAllLines(scoreOutputFileName)
.Where(x => !string.IsNullOrWhiteSpace(x))
.ToArray();
string[] temp;
for (int i = 0; i < lines.Length; i++)
{
temp = lines[i]
.Split('-')
.ToArray();
scores[temp[0].Trim()] = int.Parse(temp[1].Trim());
}
}
}
private static void PrintScores()
{
foreach (var player in scores.OrderByDescending(x => x.Value))
{
Console.WriteLine($"{player.Key}: {player.Value}");
}
}
private static void SaveScore()
{
Console.WriteLine("Enter your name:");
var name = Console.ReadLine();
if(name.Length > 0)
{
int points = CalculatePoints();
var maxScore = scores
.Max(x => x.Value);
if (maxScore < points)
{
Console.WriteLine("Highest score!!!");
}
var result = new string[] { $"\n{name} - {points}" };
scores[name] = points;
File.WriteAllLines(scoreOutputFileName, result);
}
}
public static bool GenerateNewHead()
{
Position snakeHead = snakeElements.Last();
Position nextDirection = directionOffsets[currentDirection];
Position snakeNewHead = new Position(snakeHead.X + nextDirection.X, snakeHead.Y + nextDirection.Y);
if(snakeElements.Contains(snakeNewHead))
{
EndGame();
return false;
}
if(snakeNewHead.X < 0)
{
snakeNewHead.X = Console.WindowWidth - 1;
}
if(snakeNewHead.Y < 0)
{
snakeNewHead.Y = Console.WindowHeight - 1;
}
if (snakeNewHead.X >= Console.WindowWidth)
{
snakeNewHead.X = 0;
}
if (snakeNewHead.Y >= Console.WindowHeight)
{
snakeNewHead.Y = 0;
}
snakeElements.Enqueue(snakeNewHead);
return true;
}
public static void DrawSnake()
{
foreach (Position pos in snakeElements)
{
Console.SetCursorPosition(pos.X, pos.Y);
if (snakeElements.Last().Equals(pos))
{
Console.Write(directionHead[currentDirection]);
}else
{
Console.Write(snakeSign);
}
}
}
public static void DrawFood()
{
try
{
Console.SetCursorPosition(food.X, food.Y);
}
catch (System.ArgumentOutOfRangeException e)
{
food = GenerateFood();
Console.SetCursorPosition(food.X, food.Y);
}
Console.Write(foodSign);
}
public static Position GenerateFood()
{
Position food;
do
{
food = new Position(
randomNumberGenerator.Next(0, Console.WindowWidth),
randomNumberGenerator.Next(0, Console.WindowHeight)
);
} while (snakeElements.Contains(food));
return food;
}
static void Main(string[] args)
{
bool success;
food = GenerateFood();
InitGame();
while (true)
{
Console.Clear();
DrawSnake();
//check if food is eaten
if(snakeElements.Last().X == food.X
&& snakeElements.Last().Y == food.Y)
{
sleepTime = sleepTime > 10 ? sleepTime - 10 : 10;
food = GenerateFood();
}else
{
snakeElements.Dequeue();
}
DrawFood();
if (Console.KeyAvailable)
{
CheckForDirectionChange();
}
success = GenerateNewHead();
if (!success)
{
break;
}
Thread.Sleep(sleepTime);
}
}
}
}
| 29.806452 | 111 | 0.433502 | [
"MIT"
] | AleksandrinaGeorgieva/SnakeGame | SnakeGame/Snake.cs | 8,318 | C# |
using UnityEngine;
using TMPro;
using UnityEngine.Localization.Components;
public class UIInspectorDescription : MonoBehaviour
{
[SerializeField] private LocalizeStringEvent _textDescription = default;
[SerializeField] private TextMeshProUGUI _textHealthRestoration = default;
[SerializeField] private LocalizeStringEvent _textName = default;
public void FillDescription(ItemSO itemToInspect)
{
_textName.StringReference = itemToInspect.Name;
_textName.StringReference.Arguments = new[] { new { Purpose = 0, Amount = 1 } };
_textDescription.StringReference = itemToInspect.Description;
if (itemToInspect.HealthResorationValue > 0)
{
_textHealthRestoration.text = "+" + itemToInspect.HealthResorationValue;
}
else
{
_textHealthRestoration.text = "";
}
_textName.gameObject.SetActive(true);
_textDescription.gameObject.SetActive(true);
}
}
| 30.206897 | 82 | 0.783105 | [
"Apache-2.0"
] | GFX5000i/open-project-1 | UOP1_Project/Assets/Scripts/UI/Inventory/UIInspectorDescription.cs | 878 | C# |
using System;
using Myre.UI.InputDevices;
namespace Myre.UI.Gestures
{
public class ScrollWheelMoved
: Gesture<MouseDevice>
{
public ScrollWheelMoved()
: base(false)
{
BlockedInputs.Add(1 + 5/*Enum.(typeof(MouseButtons)).Length*/);
}
protected override bool Test(MouseDevice device)
{
return Math.Abs(device.WheelMovement) > float.Epsilon;
}
}
} | 22.6 | 75 | 0.586283 | [
"MIT"
] | martindevans/Myre | Myre/Myre.UI/Gestures/ScrollWheelMoved.cs | 454 | 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("05. Bomb Numbers")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("05. Bomb Numbers")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("a5464a45-5b31-41d1-ad4b-9a69be33d4bd")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.837838 | 84 | 0.745 | [
"MIT"
] | spiderbait90/Step-By-Step-In-C-Sharp | Programming Fundamentals/Lists/05. Bomb Numbers/Properties/AssemblyInfo.cs | 1,403 | C# |
// Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
namespace StyleCop.Analyzers.SpacingRules
{
using System;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using StyleCop.Analyzers.Helpers;
using StyleCop.Analyzers.Lightup;
/// <summary>
/// A closing brace within a C# element is not spaced correctly.
/// </summary>
/// <remarks>
/// <para>A violation of this rule occurs when the spacing around a closing brace is not correct.</para>
///
/// <para>A closing brace should always be followed by a single space, unless it is the last character on the line,
/// or unless it is followed by a closing parenthesis, a comma, a semicolon, or a member access operator.</para>
///
/// <para>A closing brace should always be preceded by a single space, unless it is the first character on the
/// line.</para>
/// </remarks>
[DiagnosticAnalyzer(LanguageNames.CSharp)]
internal class SA1013ClosingBracesMustBeSpacedCorrectly : DiagnosticAnalyzer
{
/// <summary>
/// The ID for diagnostics produced by the <see cref="SA1013ClosingBracesMustBeSpacedCorrectly"/>
/// analyzer.
/// </summary>
public const string DiagnosticId = "SA1013";
private const string HelpLink = "https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1013.md";
private static readonly LocalizableString Title = new LocalizableResourceString(nameof(SpacingResources.SA1013Title), SpacingResources.ResourceManager, typeof(SpacingResources));
private static readonly LocalizableString MessageFormat = new LocalizableResourceString(nameof(SpacingResources.SA1013MessageFormat), SpacingResources.ResourceManager, typeof(SpacingResources));
private static readonly LocalizableString Description = new LocalizableResourceString(nameof(SpacingResources.SA1013Description), SpacingResources.ResourceManager, typeof(SpacingResources));
private static readonly DiagnosticDescriptor Descriptor =
new DiagnosticDescriptor(DiagnosticId, Title, MessageFormat, AnalyzerCategory.SpacingRules, DiagnosticSeverity.Warning, AnalyzerConstants.EnabledByDefault, Description, HelpLink);
private static readonly Action<SyntaxTreeAnalysisContext> SyntaxTreeAction = HandleSyntaxTree;
/// <inheritdoc/>
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } =
ImmutableArray.Create(Descriptor);
/// <inheritdoc/>
public override void Initialize(AnalysisContext context)
{
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
context.EnableConcurrentExecution();
context.RegisterSyntaxTreeAction(SyntaxTreeAction);
}
private static void HandleSyntaxTree(SyntaxTreeAnalysisContext context)
{
SyntaxNode root = context.Tree.GetCompilationUnitRoot(context.CancellationToken);
foreach (var token in root.DescendantTokens())
{
if (token.IsKind(SyntaxKind.CloseBraceToken))
{
HandleCloseBraceToken(context, token);
}
}
}
private static void HandleCloseBraceToken(SyntaxTreeAnalysisContext context, SyntaxToken token)
{
if (token.IsMissing)
{
return;
}
bool precededBySpace = token.IsFirstInLine() || token.IsPrecededByWhitespace(context.CancellationToken);
if (token.Parent is InterpolationSyntax)
{
if (precededBySpace)
{
// Closing brace should{ not} be {preceded} by a space.
var properties = TokenSpacingProperties.RemovePreceding;
context.ReportDiagnostic(Diagnostic.Create(Descriptor, token.GetLocation(), properties, " not", "preceded"));
}
return;
}
bool followedBySpace = token.IsFollowedByWhitespace();
bool lastInLine = token.IsLastInLine();
bool precedesSpecialCharacter;
if (!followedBySpace && !lastInLine)
{
SyntaxToken nextToken = token.GetNextToken();
precedesSpecialCharacter =
nextToken.IsKind(SyntaxKind.CloseParenToken)
|| nextToken.IsKind(SyntaxKind.CommaToken)
|| nextToken.IsKind(SyntaxKind.SemicolonToken)
|| nextToken.IsKind(SyntaxKind.DotToken)
|| (nextToken.IsKind(SyntaxKind.QuestionToken) && nextToken.GetNextToken(includeZeroWidth: true).IsKind(SyntaxKind.DotToken))
|| nextToken.IsKind(SyntaxKind.CloseBracketToken)
|| (nextToken.IsKind(SyntaxKind.ColonToken) && nextToken.Parent.IsKind(SyntaxKindEx.CasePatternSwitchLabel));
}
else
{
precedesSpecialCharacter = false;
}
if (!precededBySpace)
{
// Closing brace should{} be {preceded} by a space.
var properties = TokenSpacingProperties.InsertPreceding;
context.ReportDiagnostic(Diagnostic.Create(Descriptor, token.GetLocation(), properties, string.Empty, "preceded"));
}
if (!lastInLine && !precedesSpecialCharacter && !followedBySpace)
{
// Closing brace should{} be {followed} by a space.
var properties = TokenSpacingProperties.InsertFollowing;
context.ReportDiagnostic(Diagnostic.Create(Descriptor, token.GetLocation(), properties, string.Empty, "followed"));
}
}
}
}
| 47.445313 | 202 | 0.655689 | [
"MIT"
] | angelobreuer/StyleCopAnalyzers | StyleCop.Analyzers/StyleCop.Analyzers/SpacingRules/SA1013ClosingBracesMustBeSpacedCorrectly.cs | 6,075 | 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 Xunit;
namespace System.SpanTests
{
public static partial class ReadOnlySpanTests
{
[Fact]
public static void IndexOfSequenceMatchAtStart()
{
ReadOnlySpan<int> span = new ReadOnlySpan<int>(new int[] { 5, 1, 77, 2, 3, 77, 77, 4, 5, 77, 77, 77, 88, 6, 6, 77, 77, 88, 9 });
ReadOnlySpan<int> value = new ReadOnlySpan<int>(new int[] { 5, 1, 77 });
int index = span.IndexOf(value);
Assert.Equal(0, index);
}
[Fact]
public static void IndexOfSequenceMultipleMatch()
{
ReadOnlySpan<int> span = new ReadOnlySpan<int>(new int[] { 1, 2, 3, 1, 2, 3, 1, 2, 3 });
ReadOnlySpan<int> value = new ReadOnlySpan<int>(new int[] { 2, 3 });
int index = span.IndexOf(value);
Assert.Equal(1, index);
}
[Fact]
public static void IndexOfSequenceRestart()
{
ReadOnlySpan<int> span = new ReadOnlySpan<int>(new int[] { 0, 1, 77, 2, 3, 77, 77, 4, 5, 77, 77, 77, 88, 6, 6, 77, 77, 88, 9 });
ReadOnlySpan<int> value = new ReadOnlySpan<int>(new int[] { 77, 77, 88 });
int index = span.IndexOf(value);
Assert.Equal(10, index);
}
[Fact]
public static void IndexOfSequenceNoMatch()
{
ReadOnlySpan<int> span = new ReadOnlySpan<int>(new int[] { 0, 1, 77, 2, 3, 77, 77, 4, 5, 77, 77, 77, 88, 6, 6, 77, 77, 88, 9 });
ReadOnlySpan<int> value = new ReadOnlySpan<int>(new int[] { 77, 77, 88, 99 });
int index = span.IndexOf(value);
Assert.Equal(-1, index);
}
[Fact]
public static void IndexOfSequenceNotEvenAHeadMatch()
{
ReadOnlySpan<int> span = new ReadOnlySpan<int>(new int[] { 0, 1, 77, 2, 3, 77, 77, 4, 5, 77, 77, 77, 88, 6, 6, 77, 77, 88, 9 });
ReadOnlySpan<int> value = new ReadOnlySpan<int>(new int[] { 100, 77, 88, 99 });
int index = span.IndexOf(value);
Assert.Equal(-1, index);
}
[Fact]
public static void IndexOfSequenceMatchAtVeryEnd()
{
ReadOnlySpan<int> span = new ReadOnlySpan<int>(new int[] { 0, 1, 2, 3, 4, 5 });
ReadOnlySpan<int> value = new ReadOnlySpan<int>(new int[] { 3, 4, 5 });
int index = span.IndexOf(value);
Assert.Equal(3, index);
}
[Fact]
public static void IndexOfSequenceJustPastVeryEnd()
{
ReadOnlySpan<int> span = new ReadOnlySpan<int>(new int[] { 0, 1, 2, 3, 4, 5 }, 0, 5);
ReadOnlySpan<int> value = new ReadOnlySpan<int>(new int[] { 3, 4, 5 });
int index = span.IndexOf(value);
Assert.Equal(-1, index);
}
[Fact]
public static void IndexOfSequenceZeroLengthValue()
{
// A zero-length value is always "found" at the start of the span.
ReadOnlySpan<int> span = new ReadOnlySpan<int>(new int[] { 0, 1, 77, 2, 3, 77, 77, 4, 5, 77, 77, 77, 88, 6, 6, 77, 77, 88, 9 });
ReadOnlySpan<int> value = new ReadOnlySpan<int>(Array.Empty<int>());
int index = span.IndexOf(value);
Assert.Equal(0, index);
}
[Fact]
public static void IndexOfSequenceZeroLengthSpan()
{
ReadOnlySpan<int> span = new ReadOnlySpan<int>(Array.Empty<int>());
ReadOnlySpan<int> value = new ReadOnlySpan<int>(new int[] { 1, 2, 3 });
int index = span.IndexOf(value);
Assert.Equal(-1, index);
}
[Fact]
public static void IndexOfSequenceLengthOneValue()
{
// A zero-length value is always "found" at the start of the span.
ReadOnlySpan<int> span = new ReadOnlySpan<int>(new int[] { 0, 1, 2, 3, 4, 5 });
ReadOnlySpan<int> value = new ReadOnlySpan<int>(new int[] { 2 });
int index = span.IndexOf(value);
Assert.Equal(2, index);
}
[Fact]
public static void IndexOfSequenceLengthOneValueAtVeryEnd()
{
// A zero-length value is always "found" at the start of the span.
ReadOnlySpan<int> span = new ReadOnlySpan<int>(new int[] { 0, 1, 2, 3, 4, 5 });
ReadOnlySpan<int> value = new ReadOnlySpan<int>(new int[] { 5 });
int index = span.IndexOf(value);
Assert.Equal(5, index);
}
[Fact]
public static void IndexOfSequenceLengthOneValueJustPasttVeryEnd()
{
// A zero-length value is always "found" at the start of the span.
ReadOnlySpan<int> span = new ReadOnlySpan<int>(new int[] { 0, 1, 2, 3, 4, 5 }, 0, 5);
ReadOnlySpan<int> value = new ReadOnlySpan<int>(new int[] { 5 });
int index = span.IndexOf(value);
Assert.Equal(-1, index);
}
}
}
| 41.274194 | 140 | 0.54787 | [
"MIT"
] | Acidburn0zzz/corefx | src/System.Memory/tests/ReadOnlySpan/IndexOfSequence.T.cs | 5,118 | C# |
/*
* File storage API
*
* Welcome to the file-storage. You can use this API to access all file-storage endpoints. ## Base URL The base URL for all API requests is `https://unify.apideck.com` ## GraphQL Use the [GraphQL playground](https://developers.apideck.com/graphql/playground) to test out the GraphQL API. ## Headers Custom headers that are expected as part of the request. Note that [RFC7230](https://tools.ietf.org/html/rfc7230) states header names are case insensitive. | Name | Type | Required | Description | | - -- -- -- -- -- -- -- -- -- -- | - -- -- -- | - -- -- -- - | - -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - | | x-apideck-consumer-id | String | Yes | The id of the customer stored inside Apideck Vault. This can be a user id, account id, device id or whatever entity that can have integration within your app. | | x-apideck-service-id | String | No | Describe the service you want to call (e.g., pipedrive). Only needed when a customer has activated multiple integrations for the same Unified API. | | x-apideck-raw | Boolean | No | Include raw response. Mostly used for debugging purposes. | | x-apideck-app-id | String | Yes | The application id of your Unify application. Available at https://app.apideck.com/unify/api-keys. | | Authorization | String | Yes | Bearer API KEY | ## Authorization You can interact with the API through the authorization methods below. <!- - ReDoc-Inject: <security-definitions> - -> ## Pagination All API resources have support for bulk retrieval via list APIs. Apideck uses cursor-based pagination via the optional `cursor` and `limit` parameters. To fetch the first page of results, call the list API without a `cursor` parameter. Afterwards you can fetch subsequent pages by providing a cursor parameter. You will find the next cursor in the response body in `meta.cursors.next`. If `meta.cursors.next` is `null` you're at the end of the list. In the REST API you can also use the `links` from the response for added convenience. Simply call the URL in `links.next` to get the next page of results. ### Query Parameters | Name | Type | Required | Description | | - -- -- - | - -- -- - | - -- -- -- - | - -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - | | cursor | String | No | Cursor to start from. You can find cursors for next & previous pages in the meta.cursors property of the response. | | limit | Number | No | Number of results to return. Minimum 1, Maximum 200, Default 20 | ### Response Body | Name | Type | Description | | - -- -- -- -- -- -- -- -- -- -- | - -- -- - | - -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - | | meta.cursors.previous | String | Cursor to navigate to the previous page of results through the API | | meta.cursors.current | String | Cursor to navigate to the current page of results through the API | | meta.cursors.next | String | Cursor to navigate to the next page of results through the API | | meta.items_on_page | Number | Number of items returned in the data property of the response | | links.previous | String | Link to navigate to the previous page of results through the API | | links.current | String | Link to navigate to the current page of results through the API | | links.next | String | Link to navigate to the next page of results through the API | ⚠️ `meta.cursors.previous`/`links.previous` is not available for all connectors. ## SDKs and API Clients Upcoming. [Request the SDK of your choice](https://integrations.apideck.com/request). ## Debugging Because of the nature of the abstraction we do in Apideck Unify we still provide the option to the receive raw requests and responses being handled underlying. By including the raw flag `?raw=true` in your requests you can still receive the full request. Please note that this increases the response size and can introduce extra latency. ## Errors The API returns standard HTTP response codes to indicate success or failure of the API requests. For errors, we also return a customized error message inside the JSON response. You can see the returned HTTP status codes below. | Code | Title | Description | | - -- - | - -- -- -- -- -- -- -- -- -- - | - -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - | | 200 | OK | The request message has been successfully processed, and it has produced a response. The response message varies, depending on the request method and the requested data. | | 201 | Created | The request has been fulfilled and has resulted in one or more new resources being created. | | 204 | No Content | The server has successfully fulfilled the request and that there is no additional content to send in the response payload body. | | 400 | Bad Request | The receiving server cannot understand the request because of malformed syntax. Do not repeat the request without first modifying it; check the request for errors, fix them and then retry the request. | | 401 | Unauthorized | The request has not been applied because it lacks valid authentication credentials for the target resource. | | 402 | Payment Required | Subscription data is incomplete or out of date. You'll need to provide payment details to continue. | | 403 | Forbidden | You do not have the appropriate user rights to access the request. Do not repeat the request. | | 404 | Not Found | The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. | | 409 | Conflict | The request could not be completed due to a conflict with the current state of the target resource. | | 422 | Unprocessable Entity | The server understands the content type of the request entity, and the syntax of the request entity is correct but was unable to process the contained instructions. | | 5xx | Server Errors | Something went wrong with the Unify API. These errors are logged on our side. You can contact our team to resolve the issue. | ### Handling errors The Unify API and SDKs can produce errors for many reasons, such as a failed requests due to misconfigured integrations, invalid parameters, authentication errors, and network unavailability. ### Error Types #### RequestValidationError Request is not valid for the current endpoint. The response body will include details on the validation error. Check the spelling and types of your attributes, and ensure you are not passing data that is outside of the specification. #### UnsupportedFiltersError Filters in the request are valid, but not supported by the connector. Remove the unsupported filter(s) to get a successful response. #### UnsupportedSortFieldError Sort field (`sort[by]`) in the request is valid, but not supported by the connector. Replace or remove the sort field to get a successful response. #### InvalidCursorError Pagination cursor in the request is not valid for the current connector. Make sure to use a cursor returned from the API, for the same connector. #### ConnectorExecutionError A Unified API request made via one of our downstream connectors returned an unexpected error. The `status_code` returned is proxied through to error response along with their original response via the error detail. #### ConnectorProcessingError A Unified API request made via one of our downstream connectors returned a status code that was less than 400, along with a description of why the request could not be processed. Often this is due to the shape of request data being valid, but unable to be processed due to internal business logic - for example: an invalid relationship or `ID` present in your request. #### UnauthorizedError We were unable to authorize the request as made. This can happen for a number of reasons, from missing header params to passing an incorrect authorization token. Verify your Api Key is being set correctly in the authorization header. ie: `Authorization: 'Bearer sk_live_***'` #### ConnectorCredentialsError A request using a given connector has not been authorized. Ensure the connector you are trying to use has been configured correctly and been authorized for use. #### ConnectorDisabledError A request has been made to a connector that has since been disabled. This may be temporary - You can contact our team to resolve the issue. #### RequestLimitError You have reached the number of requests included in your Free Tier Subscription. You will no be able to make further requests until this limit resets at the end of the month, or talk to us about upgrading your subscription to continue immediately. #### EntityNotFoundError You've made a request for a resource or route that does not exist. Verify your path parameters or any identifiers used to fetch this resource. #### OAuthCredentialsNotFoundError When adding a connector integration that implements OAuth, both a `client_id` and `client_secret` must be provided before any authorizations can be performed. Verify the integration has been configured properly before continuing. #### IntegrationNotFoundError The requested connector integration could not be found associated to your `application_id`. Verify your `application_id` is correct, and that this connector has been added and configured for your application. #### ConnectionNotFoundError A valid connection could not be found associated to your `application_id`. Something _may_ have interrupted the authorization flow. You may need to start the connector authorization process again. #### ConnectorNotFoundError A request was made for an unknown connector. Verify your `service_id` is spelled correctly, and that this connector is enabled for your provided `unified_api`. #### OAuthRedirectUriError A request was made either in a connector authorization flow, or attempting to revoke connector access without a valid `redirect_uri`. This is the url the user should be returned to on completion of process. #### OAuthInvalidStateError The state param is required and is used to ensure the outgoing authorization state has not been altered before the user is redirected back. It also contains required params needed to identify the connector being used. If this has been altered, the authorization will not succeed. #### OAuthCodeExchangeError When attempting to exchange the authorization code for an `access_token` during an OAuth flow, an error occurred. This may be temporary. You can reattempt authorization or contact our team to resolve the issue. #### MappingError There was an error attempting to retrieve the mapping for a given attribute. We've been notified and are working to fix this issue. #### ConnectorMappingNotFoundError It seems the implementation for this connector is incomplete. It's possible this connector is in `beta` or still under development. We've been notified and are working to fix this issue. #### ConnectorResponseMappingNotFoundError We were unable to retrieve the response mapping for this connector. It's possible this connector is in `beta` or still under development. We've been notified and are working to fix this issue. #### ConnectorOperationMappingNotFoundError Connector mapping has not been implemented for the requested operation. It's possible this connector is in `beta` or still under development. We've been notified and are working to fix this issue. #### ConnectorWorkflowMappingError The composite api calls required for this operation have not been mapped entirely. It's possible this connector is in `beta` or still under development. We've been notified and are working to fix this issue. #### PaginationNotSupportedError Pagination is not yet supported for this connector, try removing limit and/or cursor from the query. It's possible this connector is in `beta` or still under development. We've been notified and are working to fix this issue. ## API Design ### API Styles and data formats #### REST API The API is organized around [REST](https://restfulapi.net/), providing simple and predictable URIs to access and modify objects. Requests support standard HTTP methods like GET, PUT, POST, and DELETE and standard status codes. JSON is returned by all API responses, including errors. In all API requests, you must set the content-type HTTP header to application/json. All API requests must be made over HTTPS. Calls made over HTTP will fail. ##### Available HTTP methods The Apideck API uses HTTP verbs to understand if you want to read (GET), delete (DELETE) or create (POST) an object. When your web application cannot do a POST or DELETE, we provide the ability to set the method through the query parameter \\_method. ``` POST /messages GET /messages GET /messages/{messageId} PATCH /messages/{messageId} DELETE /messages/{messageId} ``` Response bodies are always UTF-8 encoded JSON objects, unless explicitly documented otherwise. For some endpoints and use cases we divert from REST to provide a better developer experience. ### Schema All API requests and response bodies adhere to a common JSON format representing individual items, collections of items, links to related items and additional meta data. ### Meta Meta data can be represented as a top level member named “meta”. Any information may be provided in the meta data. It’s most common use is to return the total number of records when requesting a collection of resources. ### Idempotence (upcoming) To prevent the creation of duplicate resources, every POST method (such as one that creates a consumer record) must specify a unique value for the X-Unique-Transaction-ID header name. Uniquely identifying each unique POST request ensures that the API processes a given request once and only once. Uniquely identifying new resource-creation POSTs is especially important when the outcome of a response is ambiguous because of a transient service interruption, such as a server-side timeout or network disruption. If a service interruption occurs, then the client application can safely retry the uniquely identified request without creating duplicate operations. (API endpoints that guarantee that every uniquely identified request is processed only once no matter how many times that uniquely identifiable request is made are described as idempotent.) ### Request IDs Each API request has an associated request identifier. You can find this value in the response headers, under Request-Id. You can also find request identifiers in the URLs of individual request logs in your Dashboard. If you need to contact us about a specific request, providing the request identifier will ensure the fastest possible resolution. ### Fixed field types #### Dates The dates returned by the API are all represented in UTC (ISO8601 format). This example `2019-11-14T00:55:31.820Z` is defined by the ISO 8601 standard. The T in the middle separates the year-month-day portion from the hour-minute-second portion. The Z on the end means UTC, that is, an offset-from-UTC of zero hours-minutes-seconds. The Z is pronounced \"Zulu\" per military/aviation tradition. The ISO 8601 standard is more modern. The formats are wisely designed to be easy to parse by machine as well as easy to read by humans across cultures. #### Prices and Currencies All prices returned by the API are represented as integer amounts in a currency’s smallest unit. For example, $5 USD would be returned as 500 (i.e, 500 cents). For zero-decimal currencies, amounts will still be provided as an integer but without the need to divide by 100. For example, an amount of ¥5 (JPY) would be returned as 5. All currency codes conform to [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217). ## Support If you have problems or need help with your case, you can always reach out to our Support.
*
* The version of the OpenAPI document: 8.11.0
* Contact: hello@apideck.com
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.IO;
using System.Runtime.Serialization;
using System.Text;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using System.ComponentModel.DataAnnotations;
using OpenAPIDateConverter = Apideck.FileStorage.Client.OpenAPIDateConverter;
namespace Apideck.FileStorage.Model
{
/// <summary>
/// GetSharedLinkResponse
/// </summary>
[DataContract(Name = "GetSharedLinkResponse")]
public partial class GetSharedLinkResponse : IEquatable<GetSharedLinkResponse>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="GetSharedLinkResponse" /> class.
/// </summary>
[JsonConstructorAttribute]
protected GetSharedLinkResponse() { }
/// <summary>
/// Initializes a new instance of the <see cref="GetSharedLinkResponse" /> class.
/// </summary>
/// <param name="statusCode">HTTP Response Status Code (required).</param>
/// <param name="status">HTTP Response Status (required).</param>
/// <param name="service">Apideck ID of service provider (required).</param>
/// <param name="resource">Unified API resource name (required).</param>
/// <param name="operation">Operation performed (required).</param>
/// <param name="data">data (required).</param>
public GetSharedLinkResponse(int statusCode = default(int), string status = default(string), string service = default(string), string resource = default(string), string operation = default(string), SharedLink data = default(SharedLink))
{
this.StatusCode = statusCode;
// to ensure "status" is required (not null)
if (status == null) {
throw new ArgumentNullException("status is a required property for GetSharedLinkResponse and cannot be null");
}
this.Status = status;
// to ensure "service" is required (not null)
if (service == null) {
throw new ArgumentNullException("service is a required property for GetSharedLinkResponse and cannot be null");
}
this.Service = service;
// to ensure "resource" is required (not null)
if (resource == null) {
throw new ArgumentNullException("resource is a required property for GetSharedLinkResponse and cannot be null");
}
this.Resource = resource;
// to ensure "operation" is required (not null)
if (operation == null) {
throw new ArgumentNullException("operation is a required property for GetSharedLinkResponse and cannot be null");
}
this.Operation = operation;
// to ensure "data" is required (not null)
if (data == null) {
throw new ArgumentNullException("data is a required property for GetSharedLinkResponse and cannot be null");
}
this.Data = data;
}
/// <summary>
/// HTTP Response Status Code
/// </summary>
/// <value>HTTP Response Status Code</value>
[DataMember(Name = "status_code", IsRequired = true, EmitDefaultValue = false)]
public int StatusCode { get; set; }
/// <summary>
/// HTTP Response Status
/// </summary>
/// <value>HTTP Response Status</value>
[DataMember(Name = "status", IsRequired = true, EmitDefaultValue = false)]
public string Status { get; set; }
/// <summary>
/// Apideck ID of service provider
/// </summary>
/// <value>Apideck ID of service provider</value>
[DataMember(Name = "service", IsRequired = true, EmitDefaultValue = false)]
public string Service { get; set; }
/// <summary>
/// Unified API resource name
/// </summary>
/// <value>Unified API resource name</value>
[DataMember(Name = "resource", IsRequired = true, EmitDefaultValue = false)]
public string Resource { get; set; }
/// <summary>
/// Operation performed
/// </summary>
/// <value>Operation performed</value>
[DataMember(Name = "operation", IsRequired = true, EmitDefaultValue = false)]
public string Operation { get; set; }
/// <summary>
/// Gets or Sets Data
/// </summary>
[DataMember(Name = "data", IsRequired = true, EmitDefaultValue = false)]
public SharedLink Data { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append("class GetSharedLinkResponse {\n");
sb.Append(" StatusCode: ").Append(StatusCode).Append("\n");
sb.Append(" Status: ").Append(Status).Append("\n");
sb.Append(" Service: ").Append(Service).Append("\n");
sb.Append(" Resource: ").Append(Resource).Append("\n");
sb.Append(" Operation: ").Append(Operation).Append("\n");
sb.Append(" Data: ").Append(Data).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as GetSharedLinkResponse);
}
/// <summary>
/// Returns true if GetSharedLinkResponse instances are equal
/// </summary>
/// <param name="input">Instance of GetSharedLinkResponse to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(GetSharedLinkResponse input)
{
if (input == null)
{
return false;
}
return
(
this.StatusCode == input.StatusCode ||
this.StatusCode.Equals(input.StatusCode)
) &&
(
this.Status == input.Status ||
(this.Status != null &&
this.Status.Equals(input.Status))
) &&
(
this.Service == input.Service ||
(this.Service != null &&
this.Service.Equals(input.Service))
) &&
(
this.Resource == input.Resource ||
(this.Resource != null &&
this.Resource.Equals(input.Resource))
) &&
(
this.Operation == input.Operation ||
(this.Operation != null &&
this.Operation.Equals(input.Operation))
) &&
(
this.Data == input.Data ||
(this.Data != null &&
this.Data.Equals(input.Data))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
hashCode = (hashCode * 59) + this.StatusCode.GetHashCode();
if (this.Status != null)
{
hashCode = (hashCode * 59) + this.Status.GetHashCode();
}
if (this.Service != null)
{
hashCode = (hashCode * 59) + this.Service.GetHashCode();
}
if (this.Resource != null)
{
hashCode = (hashCode * 59) + this.Resource.GetHashCode();
}
if (this.Operation != null)
{
hashCode = (hashCode * 59) + this.Operation.GetHashCode();
}
if (this.Data != null)
{
hashCode = (hashCode * 59) + this.Data.GetHashCode();
}
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
public IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| 112.422764 | 18,155 | 0.617334 | [
"MIT"
] | grexican/apideck | src/Apideck.FileStorage/Model/GetSharedLinkResponse.cs | 27,679 | C# |
using AkshaySDemoModels;
using System.Collections.Generic;
using System.Linq;
namespace AkshaySDemoMySQL.Data
{
public class AkshaySDemoMySQLDbOperations
{
private readonly AkshaySDemoMySQLContext rc = new AkshaySDemoMySQLContext();
public IEnumerable<Recipe> GetAllRecipes()
{
try
{
return rc.Recipes.ToList();
}
catch { throw; }
}
//To Add new recipe
public void AddRecipe(Recipe recipe)
{
try
{
rc.Recipes.Add(recipe);
rc.SaveChanges();
}
catch { throw; }
}
//To Update particular recipe
public void UpdateRecipe(Recipe recipe)
{
try
{
rc.Update(recipe);
rc.SaveChanges();
}
catch { throw; }
}
//Get the particular recipe
public Recipe GetRecipe(int id)
{
try
{
Recipe recipe = rc.Recipes.Find(id);
return recipe;
}
catch
{
throw;
}
}
//To Delete particular recipe
public void DeleteRecipe(int id)
{
try
{
Recipe recipe = rc.Recipes.Find(id);
rc.Remove(recipe);
rc.SaveChanges();
}
catch
{
throw;
}
}
}
}
| 22.970588 | 84 | 0.432138 | [
"Apache-2.0"
] | akshays2112/AkshaySDemo | AkshaySDemoMySQL/Data/AkshaySDemoMySQLDbOperations.cs | 1,564 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.34014
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace SuperShell.Properties
{
/// <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 Resources
{
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources()
{
}
/// <summary>
/// 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 ((resourceMan == null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("SuperShell.Properties.Resources", typeof(Resources).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;
}
}
}
}
| 33.736111 | 161 | 0.689172 | [
"MIT"
] | kosmakoff/SuperShell | SuperShell/Properties/Resources.Designer.cs | 2,431 | C# |
using System.Runtime.InteropServices;
namespace Vulkan
{
[StructLayout(LayoutKind.Sequential)]
public struct VkPhysicalDevice8BitStorageFeatures
{
public VkStructureType SType;
[NativeTypeName("void *")] public nuint PNext;
[NativeTypeName("Bool32")] public uint StorageBuffer8BitAccess;
[NativeTypeName("Bool32")] public uint UniformAndStorageBuffer8BitAccess;
[NativeTypeName("Bool32")] public uint StoragePushConstant8;
}
}
| 25.684211 | 81 | 0.723361 | [
"BSD-3-Clause"
] | trmcnealy/Vulkan | Vulkan/Structs/VkPhysicalDevice8BitStorageFeatures.cs | 488 | C# |
using Facebook.Yoga;
using ReactNative.Bridge;
//using ReactNative.Reflection;
using ReactNative.UIManager;
using ReactNative.UIManager.Annotations;
//using ReactNative.Views.Text;
using System;
using Tizen;
using ReactNative.Common;
using Newtonsoft.Json.Linq;
namespace ReactNative.Views.TextInput
{
/// <summary>
/// This extension of <see cref="LayoutShadowNode"/> is responsible for
/// measuring the layout for Native <see cref="TextBox"/>.
/// </summary>
public class ReactTextInputShadowNode : LayoutShadowNode
{
private const int Unset = -1;
private static readonly float[] s_defaultPaddings =
{
10f,
3f,
6f,
5f,
};
private float[] _computedPadding;
private bool[] _isUserPadding = new bool[4];
/*
private FontStyle? _fontStyle;
private FontWeight? _fontWeight;
private TextAlignment _textAlignment = TextAlignment.DetectFromContent;
*/
private string _text;
private int _jsEventCount = Unset;
/// <summary>
/// Instantiates the <see cref="ReactTextInputShadowNode"/>.
/// </summary>
public ReactTextInputShadowNode()
{
SetDefaultPadding(EdgeSpacing.Start, s_defaultPaddings[0]);
SetDefaultPadding(EdgeSpacing.Top, s_defaultPaddings[1]);
SetDefaultPadding(EdgeSpacing.End, s_defaultPaddings[2]);
SetDefaultPadding(EdgeSpacing.Bottom, s_defaultPaddings[3]);
MeasureFunction = (node, width, widthMode, height, heightMode) =>
MeasureTextInput(this, node, width, widthMode, height, heightMode);
}
/// <summary>
/// Sets the text for the node.
/// </summary>
/// <param name="text">The text.</param>
[ReactProp("text")]
public void SetText(string text)
{
Log.Info(ReactConstants.Tag, "### SetText -> ReactProp('text')");
_text = text ?? "";
MarkUpdated();
}
/// <summary>
/// Set the most recent event count in JavaScript.
/// </summary>
/// <param name="mostRecentEventCount">The event count.</param>
[ReactProp("mostRecentEventCount")]
public void SetMostRecentEventCount(int mostRecentEventCount)
{
_jsEventCount = mostRecentEventCount;
}
/// <summary>
/// Called to aggregate the current text and event counter.
/// </summary>
/// <param name="uiViewOperationQueue">The UI operation queue.</param>
public override void OnCollectExtraUpdates(UIViewOperationQueue uiViewOperationQueue)
{
Log.Info(ReactConstants.Tag, "### Look, OnCollectExtraUpdates invoked ~ ");
base.OnCollectExtraUpdates(uiViewOperationQueue);
if (_computedPadding != null)
{
uiViewOperationQueue.EnqueueUpdateExtraData(ReactTag, _computedPadding);
_computedPadding = null;
}
if (_jsEventCount != Unset)
{
uiViewOperationQueue.EnqueueUpdateExtraData(ReactTag, Tuple.Create(_jsEventCount, _text));
}
}
/// <summary>
/// Sets the padding of the shadow node.
/// </summary>
/// <param name="spacingType">The spacing type.</param>
/// <param name="padding">The padding value.</param>
public override void SetPaddings(int index, JValue padding)
{
MarkUpdated();
base.SetPaddings(index, padding);
}
/// <summary>
/// Marks a node as updated.
/// </summary>
protected override void MarkUpdated()
{
base.MarkUpdated();
dirty();
}
private float[] GetComputedPadding()
{
return new[]
{
GetPadding(YogaEdge.Start),
GetPadding(YogaEdge.Top),
GetPadding(YogaEdge.End),
GetPadding(YogaEdge.Bottom),
};
}
private static YogaSize MeasureTextInput(ReactTextInputShadowNode textInputNode, YogaNode node, float width, YogaMeasureMode widthMode, float height, YogaMeasureMode heightMode)
{
textInputNode._computedPadding = textInputNode.GetComputedPadding();
var borderLeftWidth = textInputNode.GetBorder(YogaEdge.Left);
var borderRightWidth = textInputNode.GetBorder(YogaEdge.Right);
var normalizedWidth = Math.Max(0,
(YogaConstants.IsUndefined(width) ? double.PositiveInfinity : width)
- textInputNode._computedPadding[0]
- textInputNode._computedPadding[2]
- (YogaConstants.IsUndefined(borderLeftWidth) ? 0 : borderLeftWidth)
- (YogaConstants.IsUndefined(borderRightWidth) ? 0 : borderRightWidth));
var normalizedHeight = Math.Max(0, YogaConstants.IsUndefined(height) ? double.PositiveInfinity : height);
// This is not a terribly efficient way of projecting the height of
// the text elements. It requires that we have access to the
// dispatcher in order to do measurement, which, for obvious
// reasons, can cause perceived performance issues as it will block
// the UI thread from handling other work.
//
// TODO: determine another way to measure text elements.
var task = DispatcherHelpers.CallOnDispatcher(() =>
{
/*
var textBlock = new TextBlock
{
TextWrapping = TextWrapping.Wrap,
};
var normalizedText = string.IsNullOrEmpty(textNode._text) ? " " : textNode._text;
var inline = new Run { Text = normalizedText };
FormatInline(textNode, inline);
textBlock.Inlines.Add(inline);
textBlock.Measure(new Size(normalizedWidth, normalizedHeight));
var borderTopWidth = textInputNode.GetBorder(CSSSpacingType.Top);
var borderBottomWidth = textInputNode.GetBorder(CSSSpacingType.Bottom);
var finalizedHeight = (float)textBlock.DesiredSize.Height;
finalizedHeight += textInputNode._computedPadding[1];
finalizedHeight += textInputNode._computedPadding[3];
finalizedHeight += CSSConstants.IsUndefined(borderTopWidth) ? 0 : borderTopWidth;
finalizedHeight += CSSConstants.IsUndefined(borderBottomWidth) ? 0 : borderBottomWidth;
return new MeasureOutput(width, finalizedHeight);
*/
float finalizedHeight = 1;
return MeasureOutput.Make(
(float)Math.Ceiling(width),
(float)Math.Ceiling(finalizedHeight));
});
return task.Result;
}
/*
/// <summary>
/// Formats an inline instance with shadow properties.
/// </summary>
/// <param name="textNode">The text shadow node.</param>
/// <param name="inline">The inline.</param>
protected static void FormatInline(ReactTextInputShadowNode textNode, TextElement inline)
{
if (textNode._fontSize != Unset)
{
var fontSize = textNode._fontSize;
inline.FontSize = fontSize;
}
if (textNode._fontStyle.HasValue)
{
var fontStyle = textNode._fontStyle.Value;
inline.FontStyle = fontStyle;
}
if (textNode._fontWeight.HasValue)
{
var fontWeight = textNode._fontWeight.Value;
inline.FontWeight = fontWeight;
}
if (textNode._fontFamily != null)
{
var fontFamily = new FontFamily(textNode._fontFamily);
inline.FontFamily = fontFamily;
}
}
*/
}
}
| 36.903509 | 186 | 0.56299 | [
"MIT"
] | MrDG79/react-native-tizen-dotnet | Framework/ReactNet/ReactNativeTizen/Views/TextInput/ReactTextInputShadowNode.cs | 8,416 | C# |
using System.Collections.Generic;
using System.IO;
namespace Programmerare.CrsTransformations.TestData
{
// a better class name would be desirable (and then change it in the Kotlin project too)
class ResultAggregator {
private IList<FileWithRows> listOfFileWithRows = new List<FileWithRows>();
public void AddRowsFromFile(
IList<string> rowsFromFile,
FileInfo sourceFile
) {
FileWithRows fileWithRows = new FileWithRows(sourceFile, rowsFromFile);
listOfFileWithRows.Add(fileWithRows);
ISet<int> indexes = fileWithRows.GetIndexesForRowsWithSignificantDifference(fileWithRows, 0.001);
}
public ISet<int> GetIndexesForRowsWithSignificantDifference(
double deltaValueForDifferencesToIgnore
) {
ISet<int> indexes = new HashSet<int>();
for (int i = 0; i < listOfFileWithRows.Count-1; i++) {
for (int j = i+1; j < listOfFileWithRows.Count; j++) {
FileWithRows fileWithRows_i = listOfFileWithRows[i];
FileWithRows fileWithRows_j = listOfFileWithRows[j];
ISet<int> indexesForRowsWithSignificantDifference = fileWithRows_i.GetIndexesForRowsWithSignificantDifference(fileWithRows_j, deltaValueForDifferencesToIgnore);
indexes.UnionWith(indexesForRowsWithSignificantDifference);
}
}
return indexes;
}
class FileWithRows {
private FileInfo sourceFile;
private IList<string> rowsFromFile;
public FileWithRows(
FileInfo sourceFile,
IList<string> rowsFromFile
) {
this.sourceFile = sourceFile;
this.rowsFromFile = rowsFromFile;
}
public ISet<int> GetIndexesForRowsWithSignificantDifference(
FileWithRows that,
double deltaValueForDifferencesToIgnore
) {
ISet<int> indexes = new HashSet<int>();
for (int fileRowIndex = 0; fileRowIndex < rowsFromFile.Count; fileRowIndex++) {
string thisRow = this.rowsFromFile[fileRowIndex];
string thatRow = that.rowsFromFile[fileRowIndex];
TestResultItem t1 = new TestResultItem(thisRow);
TestResultItem t2 = new TestResultItem(thatRow);
DifferenceWhenComparingCoordinateValues diff = t1.IsDeltaDifferenceSignificant(t2, deltaValueForDifferencesToIgnore);
if(diff == DifferenceWhenComparingCoordinateValues.SIGNIFICANT_VALUE_DIFFERENCE) {
indexes.Add(fileRowIndex);
}
}
return indexes;
}
}
}
} | 39.969697 | 176 | 0.657316 | [
"MIT"
] | TomasJohansson/crsTransformations-dotnet | TestAndExampleProjects/Programmerare.CrsTransformations.Test/TestData/ResultAggregator.cs | 2,638 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using benchmark;
using System.Globalization;
namespace oop_c_
{
class Program
{
static double TRAIN_TEST_SPLIT = 0.1;
static double LEARNING_RATE = 0.3;
static int N_EPOCHS = 500;
static int N_HIDDEN = 5;
static void Main(string[] args)
{
var iterations = args.Length > 0 ? int.Parse(args[0]) : 1;
var bm = new Benchmark(iterations);
var file = File.ReadAllLines("benchmarks/NN/wheat-seeds.csv");
bm.Run(() => {
var dataset = Utils.NormaliseColumns(Utils.LoadCSV(file));
(double[,] test, double[,] train) = Utils.GetTestTrainSplit(dataset, TRAIN_TEST_SPLIT);
(double[,] testData, double[] testActual) = (test.GetCols(0, test.GetLength(1) - 2), test.GetCol(test.GetLength(1) - 1));
(double[,] trainData, double[] trainActual) = (train.GetCols(0, train.GetLength(1) - 2), train.GetCol(train.GetLength(1) - 1));
int nInputs = train.GetLength(1);
int nOutputs = trainActual.Distinct().Count();
NeuralNetwork network = new NeuralNetwork(new AccuracyPercentage()).InitialiseLayers(nInputs, N_HIDDEN, nOutputs);
network.Train(train, trainActual, LEARNING_RATE, N_EPOCHS);
(int[] predictions, double accuracy) = network.Predict(test, testActual);
return accuracy;
}, (res) => {
System.Console.WriteLine(res);
});
}
static int getDistinctCount(double[] arr)
{
HashSet<double> distinct = new HashSet<double>();
foreach(double i in arr)
distinct.Add(i);
return distinct.Count;
}
}
public static class Utils
{
public static double[,] LoadCSV(string[] file)
{
double[,] dataset = new double[file.Length, file[0].Split(',').Length];
for (int i = 0; i < file.Length; i++)
{
var values = file[i].Split(',');
for (int j = 0; j < values.Length; j++)
{
if (j == values.Length - 1)
dataset[i, j] = double.Parse(values[j], CultureInfo.InvariantCulture) - 1;
else
dataset[i, j] = double.Parse(values[j], CultureInfo.InvariantCulture);
}
}
return dataset;
}
public static double[,] NormaliseColumns(double[,] dataset)
{
int numColumns = dataset.GetLength(1) - 1;
for (int i = 0; i < numColumns; i++)
{
double[] column = dataset.GetCol(i);
(double min, double max) = minMax(column);
double diff = max - min;
for (int j = 0; j < column.Length; j++)
dataset[j, i] = (dataset[j, i] - min) / diff;
}
return dataset;
}
public static (double, double) minMax (double[] arr){
var (min, max) = (arr[0], arr[0]);
for (int i = 1; i < arr.Length; i++)
{
if (arr[i] > max)
max = arr[i];
if (arr[i] < min)
min = arr[i];
}
return (min, max);
}
public static (double[,], double[,]) GetTestTrainSplit(double[,] dataset, double percent)
{
dataset = shuffle(dataset);
(int rows, int columns) = (dataset.GetLength(0), dataset.GetLength(1));
int numTest = (int)(rows * percent);
int numTrain = rows - numTest;
double[,] test = new double[numTest, columns];
double[,] train = new double[numTrain, columns];
int testindex = 0;
int trainindex = 0;
for (int i = 0; i < rows; i++)
{
if (i < numTest)
test.SetRow(testindex++, dataset.GetRow(i));
else
train.SetRow(trainindex++, dataset.GetRow(i));
}
return (test, train);
}
private static T[,] shuffle<T>(T[,] array)
{
T[,] shuffledArray = new T[array.GetLength(0), array.GetLength(1)];
int numRows = array.GetLength(0);
Random rnd = new Random(3);
for (int i = 0; i < numRows; i++)
{
int randIndex = rnd.Next(0, numRows);
// swap procedure
var h = array.GetRow(i);
shuffledArray.SetRow(i, array.GetRow(randIndex));
shuffledArray.SetRow(randIndex, h);
}
return shuffledArray;
}
}
public class NeuralNetwork
{
int nOutputs { get; set; }
List<Layer> layers { get; set; }
IAccuracyMetric accuracyMetric { get; set; }
public NeuralNetwork(IAccuracyMetric accuracyMetric)
{
this.accuracyMetric = accuracyMetric;
}
public NeuralNetwork InitialiseLayers(int nInputs, int nHidden, int nOutputs)
{
this.nOutputs = nOutputs; // Output neurons
layers = new List<Layer>();
Layer hidden = new Layer(nHidden, nInputs + 1, null, new SigmoidActivation());
Layer output = new Layer(nOutputs, nHidden + 1, hidden, new SigmoidActivation());
layers.Add(hidden);
layers.Add(output);
return this;
}
public (int[], double) Predict(double[,] testData, double[] testActual)
{
int numTestRows = testData.GetLength(0);
int[] predictions = new int[numTestRows];
for (int i = 0; i < numTestRows; i++)
predictions[i] = PredictRow(testData.GetRow(i));
double accuracy = accuracyMetric.ComputeAccuracy(testActual, predictions);
return (predictions, accuracy);
}
private int PredictRow(double[] row)
{
double[] outputs = ForwardPropagate(row);
double max = outputs[0];
int index = 0;
for (int j = 1; j < outputs.Length; j++)
if (outputs[j] > max)
{
max = outputs[j];
index = j;
}
return index;
}
public double[] ForwardPropagate(double[] inputs)
{
foreach (Layer layer in layers)
inputs = layer.ForwardPropagate(inputs);
return inputs;
}
public void BackPropagateError(double[] expected)
{
int length = layers.Count - 1;
// Iterating through layers, staring with the ouput layer
// This ensures that the neurons in the output layer have ‘delta’
// values calculated first that neurons in the hidden layer can use
// in the subsequent iteration.
for (int i = length; i >= 0; i--)
{
Layer layer = layers[i];
List<double> errors = new List<double>();
// Iterating through all neurons in the layer
int numNeurons = layer.Neurons.Length;
for (int j = 0; j < numNeurons; j++)
{
Neuron n = layer.Neurons[j];
// If output layer
if (i == length)
errors.Add(expected[j] - n.Output);
// If hidden layer
else
{
double error = 0.0;
// Accumulate error based on neurons in the next layer
foreach (Neuron neuron in layers[i + 1].Neurons)
error += neuron.Weights[j] * neuron.Delta;
errors.Add(error);
}
n.Delta = errors[j] * n.Derivative;
}
}
}
public void Train(double[,] trainData, double[] trainActual, double learningRate, int nEpochs)
{
for (int i = 0; i < nEpochs; i++)
{
double sumError = 0;
int len = trainData.GetLength(0);
// For each row in the training data
for (int j = 0; j < len; j++)
{
double[] features = trainData.GetRow(j);
double actual = trainActual[j];
double[] outputs = ForwardPropagate(features);
double[] expected = new double[nOutputs];
expected[(int)actual] = 1;
// Calculate Error
sumError += SumSquaredError(outputs, expected);
// Calculate Gradient and Delta
BackPropagateError(expected);
// Adjust weights and biases
updateWeights(features, learningRate);
}
}
}
private double SumSquaredError(double[] outputs, double[] expected)
{
double res = 0;
for (int p = 0; p < nOutputs; p++)
res += Math.Pow(expected[p] - outputs[p], 2);
return res;
}
private void updateWeights(double[] row, double learning_rate)
{
foreach (Layer layer in layers)
layer.UpdateWeights(row, learning_rate);
}
}
public class Layer
{
public Neuron[] Neurons { get; set; }
int numNeurons { get; set; }
Layer previousLayer { get; set; }
public Layer(int nNeurons, int nNeuronInputConnections, Layer previous, IActivationStrategy activation)
{
numNeurons = nNeurons;
previousLayer = previous;
Neurons = new Neuron[nNeurons];
// Adds specified neurons
for (int i = 0; i < nNeurons; i++)
Neurons[i] = new Neuron(nNeuronInputConnections, activation);
}
public double[] ForwardPropagate(double[] inputs)
{
double[] newInputs = new double[inputs.Length];
for (int i = 0; i < Neurons.Length; i++)
newInputs[i] = Neurons[i].Activate(inputs);
return newInputs;
}
public void UpdateWeights(double[] row, double learningRate)
{
double[] inputs = row[0..^1];
if (previousLayer != null)
{
Neuron[] neuronsInPreviousLayer = previousLayer.Neurons;
inputs = new double[neuronsInPreviousLayer.Length];
for (int neuron = 0; neuron < neuronsInPreviousLayer.Length; neuron++)
inputs[neuron] = neuronsInPreviousLayer[neuron].Output;
}
foreach (Neuron n in Neurons)
{
for (int j = 0; j < inputs.Length; j++)
n.Weights[j] += learningRate * n.Delta * inputs[j];
n.Weights[^1] += learningRate * n.Delta;
}
}
}
public class Neuron
{
static Random rnd = new Random(2);
public double[] Weights { get; set; }
public double Output { get; set; }
public double Delta { get; set; }
IActivationStrategy actvationFunction { get; set; }
public double Derivative
{
// Calculate the derivative of an neuron output
// using the sigmoid transfer function
get => Output * (1 - Output);
}
public Neuron(int nInputs, IActivationStrategy activationFunction)
{
this.actvationFunction = activationFunction;
Weights = new double[nInputs];
Delta = 0;
// Random weights for each input to the neuron
for (int i = 0; i < nInputs; i++)
{
Weights[i] = rnd.NextDouble();
}
}
public double Activate(double[] inputs)
{
Output = actvationFunction.Activate(Weights, inputs);
return Output;
}
}
public interface IActivationStrategy
{
double Activate(double[] weights, double[] inputs);
}
public class SigmoidActivation : IActivationStrategy
{
public double Activate(double[] weights, double[] inputs)
{
int length = weights.Length - 1;
// This is bias
double activation = weights[length];
for (int i = 0; i < length; i++)
activation += weights[i] * inputs[i];
return 1.0 / (1.0 + Math.Exp(-activation));
}
}
public interface IAccuracyMetric
{
double ComputeAccuracy(double[] actual, int[] predictions);
}
public class AccuracyPercentage : IAccuracyMetric
{
public double ComputeAccuracy(double[] actual, int[] predictions)
{
int correct = 0;
int numPredictions = predictions.Length;
for (int i = 0; i < numPredictions; i++)
if (actual[i] == predictions[i])
correct++;
return ((double)correct / numPredictions) * 100;
}
}
public static class MatrixExtensions
{
/// <summary>
/// Returns the row with number 'row' of this matrix as a 1D-Array.
/// </summary>
public static T[] GetRow<T>(this T[,] matrix, int row)
{
var rowLength = matrix.GetLength(1);
var rowVector = new T[rowLength];
for (var i = 0; i < rowLength; i++)
rowVector[i] = matrix[row, i];
return rowVector;
}
/// <summary>
/// Sets the row with number 'row' of this 2D-matrix to the parameter 'rowVector'.
/// </summary>
public static void SetRow<T>(this T[,] matrix, int row, T[] rowVector)
{
var rowLength = matrix.GetLength(1);
for (var i = 0; i < rowLength; i++)
matrix[row, i] = rowVector[i];
}
/// <summary>
/// Returns the column with number 'col' of this matrix as a 1D-Array.
/// </summary>
public static T[] GetCol<T>(this T[,] matrix, int col)
{
var colLength = matrix.GetLength(0);
var colVector = new T[colLength];
for (var i = 0; i < colLength; i++)
colVector[i] = matrix[i, col];
return colVector;
}
public static T[,] GetCols<T>(this T[,] matrix, int start, int end)
{
var rowLength = matrix.GetLength(0);
var cols = new T[rowLength, end - start];
for (int i = start; i < end; i++)
for (var j = 0; j < rowLength; j++)
cols[j, i - start] = matrix[j, i];
return cols;
}
}
}
| 36.305687 | 132 | 0.491221 | [
"MIT"
] | lrecht/ParadigmComparison | benchmarks/NN/oop_c#/Program.cs | 15,327 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using ET;
using System;
using System.Reflection;
namespace EGamePlay.Combat
{
public static class ConfigHelper
{
public static T Get<T>(int id) where T : class, IConfig
{
return ConfigManageComponent.Instance.Get<T>(id);
}
public static Dictionary<int, T> GetAll<T>() where T : class, IConfig
{
return ConfigManageComponent.Instance.GetAll<T>();
}
}
public class ConfigManageComponent : Component
{
public static ConfigManageComponent Instance { get; private set; }
public Dictionary<Type, object> TypeConfigCategarys { get; set; } = new Dictionary<Type, object>();
public override void Setup(object initData)
{
Instance = this;
var assembly = Assembly.GetAssembly(typeof(TimerManager));
var configsCollector = initData as ReferenceCollector;
if (configsCollector == null)
{
return;
}
foreach (var item in configsCollector.data)
{
var configTypeName = $"ET.{item.gameObject.name}";
var configType = assembly.GetType(configTypeName);
var typeName = $"ET.{item.gameObject.name}Category";
var configCategoryType = assembly.GetType(typeName);
var configCategory = Activator.CreateInstance(configCategoryType) as ACategory;
configCategory.ConfigText = (item.gameObject as TextAsset).text;
configCategory.BeginInit();
TypeConfigCategarys.Add(configType, configCategory);
}
}
public T Get<T>(int id) where T : class, IConfig
{
var category = TypeConfigCategarys[typeof(T)] as ACategory<T>;
return category.Get(id);
}
public Dictionary<int, T> GetAll<T>() where T : class, IConfig
{
var category = TypeConfigCategarys[typeof(T)] as ACategory<T>;
return category.GetAll();
}
}
} | 33.968254 | 107 | 0.597664 | [
"MIT"
] | ErQing/EGamePlay | Assets/EGamePlay/Component/ConfigManageComponent.cs | 2,142 | C# |
namespace Shuhari.WinTools.Core.Features.SysOptimize
{
/// <summary>
/// 系统优化
/// </summary>
public class Feature : BaseFeature
{
}
}
| 15.9 | 53 | 0.591195 | [
"MIT"
] | shuhari/Shuhari.WinTools | Shuhari.WinTools.Core/Features/SysOptimize/Feature.cs | 169 | C# |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
namespace EvidenceZvirat
{
public class SpravceZvirat: INotifyPropertyChanged
{
#region Konstruktor / atributy / kolekce
public event PropertyChangedEventHandler PropertyChanged;
// *********************************************** Kolekce pro PRASE ***********************************************
/// <summary>
/// Kolekce všech selat, tedy pro obě PRASNICE
/// </summary>
public ObservableCollection<Prase> SeznamSelat { get; set; }
/// <summary>
/// Veterinární záznamy pro všechna Prasat i Prasnice
/// </summary>
public ObservableCollection<Veterina> SeznamVeterinarnichZaznamu_Prase { get; set; }
/// <summary>
/// Vybrané veterinární záznamy pro konkrétní PRASE
/// </summary>
public ObservableCollection<Veterina> ZaznamySelete { get; set; }
/// <summary>
/// Kolekce všech porodů PRASNIC
/// </summary>
public ObservableCollection<Porod> PorodyPrase { get; set; }
/// <summary>
/// Vytříděnná selata pro první PRASNICI - chovatel pojmenoval jako MARUSKA
/// </summary>
public ObservableCollection<Prase> SeleMaruska { get; set; }
/// <summary>
/// Vytříděnná selata pro druhou PRASNICI - chovatel pojmenoval jako BARUSKA
/// </summary>
public ObservableCollection<Prase> SeleBaruska { get; set; }
/// <summary>
/// Všechny výdajové transakce pro PRASE
/// </summary>
public ObservableCollection<Finance> VydajePrase { get; set; }
/// <summary>
/// Všechny příjmové transakce pro PRASE
/// </summary>
public ObservableCollection<Finance> PrijmyPrase { get; set; }
// *********************************************** Kolekce pro OVCE ***********************************************
/// <summary>
/// Kolekce pro uložení dospělých OVCI
/// </summary>
public ObservableCollection<Ovce> SeznamOvci { get; set; }
/// <summary>
/// Kolekce pro uložení JEHŇAT
/// </summary>
public ObservableCollection<Ovce> SeznamJehnat { get; set; }
/// <summary>
/// Kolekce pro uložení BERANU
/// </summary>
public ObservableCollection<Ovce> SeznamBeranu { get; set; }
/// <summary>
/// Kolekce pro všechy porody
/// </summary>
public ObservableCollection<Porod> PorodyOvce { get; set; }
/// <summary>
/// Kolekce pro všechy veterinární záznamy
/// </summary>
public ObservableCollection<Veterina> SeznamVeterinarnichZaznamu_Ovce { get; set; }
/// <summary>
/// Kolekce pro výdajové transakce
/// </summary>
public ObservableCollection<Finance> VydajeOvce { get; set; }
/// <summary>
/// Kolekce pro příjmové transakce
/// </summary>
public ObservableCollection<Finance> PrijmyOvce { get; set; }
/// <summary>
/// Kolekce pro všecha odčervení
/// </summary>
public ObservableCollection<Odcerveni> SeznamOdcerveni { get; set;}
/// <summary>
/// Kolekce pro všechna očkování
/// </summary>
public ObservableCollection<Ockovani> SeznamOckovani { get; set; }
// *********************************************** Cesty pro uložení dat na C/user/appData ***********************************************
private string cestaOvce;
private string cestaJehnata;
private string cestaBerani;
private string cestaPrase;
private string cestaVeterina;
private string cestaVeterina_Ovce;
private string cestaPrijmyPrase;
private string cestaVydajePrase;
private string cestaPrijmyOvce;
private string cestaVydajeOvce;
private string cestaID;
private string cestaPorodyPrase;
private string cestaPorodyOvce;
private string cestaOckovani;
private string cestaOdcerveni;
private string cesta = "";
/// <summary>
/// Uložená hodnota zisku OVCE
/// </summary>
public double ZiskOvce { get; set; }
/// <summary>
/// Hodnota zisku PRASE
/// </summary>
public double ZiskPrase { get; set; }
/// <summary>
/// První PRASNICE projektu - chovatel pojmenoval jako MARUSKA
/// </summary>
public Svine Maruska { get; set; }
/// <summary>
/// Druhá PRASNICE projektu - chovatel pojmenoval jako BARUSKA
/// </summary>
public Svine Baruska { get; set; }
private Ovce matka_pomocna;
private Ovce otec_pomocna;
// *********************************************** Identifikátory pro všechny třídy ***********************************************
public int ID_Porod_Prase { get; set; }
public int ID_Porod_Ovce { get; set; }
public int ID_Sele { get; set; }
public int ID_Ovce { get; set; }
public int ID_Jehne { get; set; }
public int ID_Beran { get; set; }
public int ID_Veterina_Prase { get; set; }
public int ID_Finance_Prase { get; set; }
public int ID_Finance_Ovce { get; set; }
public int ID_Veterina_Ovce { get; set; }
public int ID_Odcerveni { get; set; }
public int ID_Ockovani{ get; set; }
/// <summary>
/// Základní konstruktor správce aplikace
/// </summary>
public SpravceZvirat()
{
// Počáteční hodnoty ID - přidalších startech budou přemazány hodnotami ze souboru
ID_Finance_Prase = 0;
ID_Finance_Ovce = 0;
ID_Ovce = 0;
ID_Jehne = 0;
ID_Beran = 0;
ID_Porod_Prase = 0;
ID_Sele = 2;
ID_Veterina_Prase = 0;
ID_Veterina_Ovce = 0;
ID_Odcerveni = 0;
ID_Ockovani = 0;
ID_Porod_Ovce = 0;
// Vytvoření cesty do složky AppData na disku C - do složky EvidenceZvirat, ktera se případně vytvoří
try
{
cesta = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "EvidenceZvirat");
if (!Directory.Exists(cesta))
Directory.CreateDirectory(cesta);
}
catch
{
Console.WriteLine("Nepodařilo se vytvořit složku {0}, zkontrolujte prosím svá oprávnění.", cesta);
}
// Uložení cest ke všem souborům obsahujícím všechny kolekce projektu - složka EvidenceZvirat v AppData na disku C
cestaOvce = Path.Combine(cesta,"ovce.xml");
cestaJehnata = Path.Combine(cesta, "jehnata.xml");
cestaBerani = Path.Combine(cesta, "berani.xml");
cestaPrase = Path.Combine(cesta, "prase.xml");
cestaVeterina = Path.Combine(cesta, "veterina.xml");
cestaVeterina_Ovce = Path.Combine(cesta, "vetrina_ovce.xml");
cestaPrijmyPrase = Path.Combine(cesta, "prijmyPrase.xml");
cestaVydajePrase = Path.Combine(cesta, "vydajePrase.xml");
cestaPrijmyOvce = Path.Combine(cesta, "prijmyOvce.xml");
cestaVydajeOvce = Path.Combine(cesta, "vydajeOvce.xml");
cestaID = Path.Combine(cesta, "id.xml");
cestaPorodyPrase = Path.Combine(cesta, "porodyPrase.xml");
cestaPorodyOvce = Path.Combine(cesta, "porodyOvce.xml");
cestaOckovani = Path.Combine(cesta, "ockovani.xml");
cestaOdcerveni = Path.Combine(cesta, "odcerveni.xml");
// PRASE
SeznamSelat = new ObservableCollection<Prase>();
SeznamVeterinarnichZaznamu_Prase = new ObservableCollection<Veterina>();
ZaznamySelete = new ObservableCollection<Veterina>();
SeleBaruska = new ObservableCollection<Prase>();
SeleMaruska = new ObservableCollection<Prase>();
VydajePrase = new ObservableCollection<Finance>();
PrijmyPrase = new ObservableCollection<Finance>();
PorodyPrase = new ObservableCollection<Porod>();
// OVCE
SeznamOvci = new ObservableCollection<Ovce>();
SeznamJehnat = new ObservableCollection<Ovce>();
SeznamBeranu = new ObservableCollection<Ovce>();
SeznamVeterinarnichZaznamu_Ovce = new ObservableCollection<Veterina>();
VydajeOvce = new ObservableCollection<Finance>();
PrijmyOvce = new ObservableCollection<Finance>();
PorodyOvce = new ObservableCollection<Porod>();
SeznamOckovani = new ObservableCollection<Ockovani>();
SeznamOdcerveni = new ObservableCollection<Odcerveni>();
// Definice dvou PRASNIC, které má chovatel
Maruska = new Svine("Maruska",0, new DateTime(2017,5,1));
Baruska = new Svine("Baruska",1, new DateTime(2018, 5, 1));
// Prazdne ovce pro ulozeni zakladnich ovci, jejich matky a ovce
matka_pomocna = new Ovce(ID_Ovce,"0", new DateTime(1, 1, 1));
ID_Ovce++;
otec_pomocna = new Ovce(ID_Beran,"0", new DateTime(1, 1, 1));
ID_Beran++;
}
/// <summary>
/// Metoda, ktera dokaze vyvolat zmenu na Observaiblle Collection a tim zmenit seznam
/// </summary>
/// <param name="vlastnost">Nazev zmeneneho atributu, vlastnosti</param>
protected void VyvolejZmenu(string vlastnost)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(vlastnost));
}
#endregion
// **************************************
#region Finance
/// <summary>
/// Spočítá zisk pro daný druh zvířete
/// </summary>
/// <param name="zvire">0 - Prase, 1 - Ovce</param>
public void SpocitejZisk(byte zvire)
{
double sumaVydej = 0;
double sumaPrijem = 0;
bool pocitej = true;
ObservableCollection<Finance> Vydaje = new ObservableCollection<Finance>();
ObservableCollection<Finance> Prijmy = new ObservableCollection<Finance>();
// Prase - přiřezení požadovaných kolekcí
if (zvire == 0)
{
Vydaje = VydajePrase;
Prijmy = PrijmyPrase;
}
// Ovce - přiřezení požadovaných kolekcí
else if (zvire == 1)
{
Vydaje = VydajeOvce;
Prijmy = PrijmyOvce;
}
else
pocitej = false;
// Výpočet zisků
if (Vydaje != null && Prijmy != null && pocitej)
{
foreach (Finance d in Vydaje)
sumaVydej += d.Castka;
foreach (Finance d in Prijmy)
sumaPrijem += d.Castka;
if (zvire == 0)
ZiskPrase = sumaPrijem - sumaVydej;
else if (zvire == 1)
ZiskOvce = sumaPrijem - sumaVydej;
}
// Vyvolání metody a následně události, která oznamuje změnu v Atributech, aby se data na formuláři aktualizovali
VyvolejZmenu("ZiskPrase");
VyvolejZmenu("ZiskOvce");
}
/// <summary>
/// Metoda spocita naklady na dany vrh, pro danou matku apod - pro OVCE i PRASE
/// </summary>
/// <param name="typBilance">0 - Vydaje, 1 - Prijmy</param>
/// <param name="zvire">0 - Prase, 1 - Ovce</param>
/// <param name="konkretniZvire">0 - Marus, 1 - Barus, 2 - Ostatni, 3 - Vrh, 4 - Ovce, 5 - Rok</param>
/// <param name="evidencniCislo">Evidencni cislo ovce</param>
/// <param name="cisloVrhu">Cislo vrhu</param>
/// <returns></returns>
public double SpocitejBilanci(byte typBilance, byte zvire, byte konkretniZvire, string evidencniCislo, byte cisloVrhu, int cisloRoku)
{
ObservableCollection<Finance> seznam = new ObservableCollection<Finance>();
string pocitanyObjekt = "";
double sumaVydaje = 0;
// Výdaje
if (typBilance == 0)
{
// Prase
if (zvire == 0)
{
seznam = VydajePrase;
// První prasnice
if (konkretniZvire == 0)
pocitanyObjekt = "maruska";
// Druhá prasnice
else if (konkretniZvire == 1)
pocitanyObjekt = "baruska";
// Vedlejší výdaje - stavby apod.
else if (konkretniZvire == 2)
pocitanyObjekt = "ostatni";
}
// Ovce
else if (zvire == 1)
{
seznam = VydajeOvce;
pocitanyObjekt = evidencniCislo;
// Ostatní - stavby apod
if (konkretniZvire == 2)
pocitanyObjekt = "ostatni";
}
}
// Příjmy
else if (typBilance == 1)
{
// Prase
if (zvire == 0)
{
seznam = PrijmyPrase;
if (konkretniZvire == 0)
pocitanyObjekt = "maruska";
else if (konkretniZvire == 1)
pocitanyObjekt = "baruska";
else if (konkretniZvire == 2)
pocitanyObjekt = "ostatni";
}
// Ovce
else if (zvire == 1)
{
seznam = PrijmyOvce;
pocitanyObjekt = evidencniCislo;
if (konkretniZvire == 2)
pocitanyObjekt = "ostatni";
}
}
// Vypocet Bilance pro danou PRASNICI, ostatní (stavby apod.) nebo OVCI
if (konkretniZvire == 0 || konkretniZvire == 1 || konkretniZvire == 2 || konkretniZvire == 4)
{
foreach (Finance f in seznam)
{
if (f.Matka == pocitanyObjekt)
sumaVydaje += f.Castka;
}
}
// Vypocet bilance pro dany rok pro OVCE
if (cisloRoku > 0 && konkretniZvire == 5)
{
foreach (Finance f in seznam)
{
if (f.Datum.Year == cisloRoku)
sumaVydaje += f.Castka;
}
}
// Vypocet bilance pro dany vrh
// Nebo tako vypocet pro vybranou generaci u ovci
if (cisloVrhu != 0 && konkretniZvire == 3)
{
foreach (Finance f in seznam)
{
if (f.CisloVrhu == cisloVrhu)
sumaVydaje += f.Castka;
}
}
return sumaVydaje;
}
/// <summary>
/// Metoda, ktera pracuje s financnimi zaznamy jak pro PRASE, tak pro OVCE
/// </summary>
/// <param name="naz">Nazev transakce</param>
/// <param name="pop">Popis transakce</param>
/// <param name="cast">Castka v CZK</param>
/// <param name="matka">Matka nebo vztazna ovce, tedy jeji EV. cislo</param>
/// <param name="vrh">Vrh u prasat nebo generace u ovci, ke které se má transakce vztahovat</param>
/// <param name="datum">Datum transakce</param>
/// <param name="typ">0 - Vydaje, 1 - Prijmy</param>
/// <param name="zvire">0 - Prase, 1 - Ovce</param>
/// <param name="operace">0 - Novy zaznam, 1 - Uprava stavajiciho</param>
/// <param name="zaznam">Financni zaznam pro upravu stavajiciho</param>
public bool ZadejFinanceZaznam(string naz, string pop, string cast, string matka, string vrh, string datum, byte typ, byte zvire, byte operace, Finance zaznam)
{
// pomocná kolekce, které se přiřadí reference na požadovanou kolekci na dalších řádcích
ObservableCollection<Finance> seznam = new ObservableCollection<Finance>();
byte vrhPomocna = 0;
bool odpoved = false;
double castkaPomocna = 0;
DateTime datumPomocna;
// Prase
if (zvire == 0)
{
// Výdaje
if (typ == 0)
seznam = VydajePrase;
else
seznam = PrijmyPrase;
}
// Ovce
else if (zvire == 1)
{
// Výdaje
if (typ == 0)
seznam = VydajeOvce;
else
seznam = PrijmyOvce;
}
// ---------------------- Ošetření vstupů pomocí vyjímek ----------------------
if (datum == "")
throw new ArgumentException("Nezadal jsi žádné datum transakce.");
else
datumPomocna = DateTime.Parse(datum).Date;
if (datumPomocna > DateTime.Now)
throw new ArgumentException("Zadal jsi datum z budoucnosti.");
if (naz == "")
throw new ArgumentException("Nezadal jsi žádný název transakce.");
if (cast == "")
throw new ArgumentException("Nezadal jsi žádnou částku.");
if (pop == "")
pop = "Nic";
// Vrh u prasatek | Generace pro ovce
if (vrh != "")
vrhPomocna = byte.Parse(vrh);
if (cast != "")
castkaPomocna = double.Parse(cast);
// Kontrola a doplneni pro prase
if (zvire == 0)
{
if (matka.StartsWith("mar"))
matka = "maruska";
if (matka.StartsWith("bar"))
matka = "baruska";
if (matka != "maruska" && matka != "baruska" && vrhPomocna == 0)
matka = "ostatni";
}
// Kontrola a doplneni pro OVCE
if (zvire == 1)
{
if (matka == "" && vrhPomocna == 0)
matka = "ostatni";
if (matka == "" && vrhPomocna > 0)
matka = "zadna";
}
int pomocna;
// Vytvoreni noveho zaznamu
if (operace == 0)
{
int ID_Finance = 0;
// Prase
if (zvire == 0)
{
ID_Finance = ID_Finance_Prase;
ID_Finance_Prase++;
}
// Ovce
else if (zvire == 1)
{
ID_Finance = ID_Finance_Ovce;
ID_Finance_Ovce++;
}
// Přidání záznamu do kolekce
seznam.Add(new Finance(ID_Finance, naz, pop, castkaPomocna, matka, vrhPomocna, typ, datumPomocna));
odpoved = true;
}
// Úprava stavajiciho zaznamu
else if (operace == 1)
{
pomocna = seznam.IndexOf(zaznam);
seznam[pomocna].CisloVrhu = vrhPomocna;
seznam[pomocna].Castka = castkaPomocna;
seznam[pomocna].Popis = pop;
seznam[pomocna].Matka = matka;
seznam[pomocna].Nazev = naz;
seznam[pomocna].Datum = datumPomocna;
odpoved = true;
}
VyvolejZmenu("VydajeOvce");
VyvolejZmenu("PrijmyOvce");
VyvolejZmenu("VydajePrase");
VyvolejZmenu("PrijmyPrase");
UlozVydaje(0);
UlozVydaje(1);
UlozPrijmy(0);
UlozPrijmy(1);
UlozID();
return odpoved;
}
/// <summary>
/// Odebrání záznamu ze seznamu financí (pro Prase či Ovci - Příjem či Výdaj)
/// </summary>
/// <param name="zaznam">Object FINANCE, tedy vybraný záznam z ListBox</param>
/// <param name="zvire">0 - Prase, 1 - Ovce</param>
/// <param name="typ">0 - Výdaj, 1 - Příjem</param>
public bool OdeberFinancniZaznam(Finance zaznam, byte zvire, byte typ)
{
bool odpoved = false;
ObservableCollection<Finance> seznam = new ObservableCollection<Finance>();
if (zvire == 0)
{
if (typ == 0)
seznam = VydajePrase;
else
seznam = PrijmyPrase;
}
else if (zvire == 1)
{
if (typ == 0)
seznam = VydajeOvce;
else
seznam = PrijmyOvce;
}
if (zaznam != null)
{
int zalohaID = seznam.IndexOf(zaznam);
seznam.Remove(zaznam);
foreach (Finance f in seznam)
{
if (f.ID > zalohaID)
f.ID--;
}
if (zvire == 0)
ID_Finance_Prase--;
else if (zvire == 1)
ID_Finance_Ovce--;
VyvolejZmenu("VydajeOvce");
VyvolejZmenu("PrijmyOvce");
VyvolejZmenu("VydajePrase");
VyvolejZmenu("PrijmyPrase");
UlozVydaje(0);
UlozVydaje(1);
UlozPrijmy(0);
UlozPrijmy(1);
UlozID();
odpoved = true;
}
return odpoved;
}
/// <summary>
/// Seřadí příjmy a výdaje pro PRASE sestupně, tedy poslední nahoře
/// </summary>
public void SeradFinance()
{
// Výdaje
IEnumerable<Finance> serazeny = VydajePrase.OrderByDescending(a => a.ID);
VydajePrase = new ObservableCollection<Finance>();
foreach (Finance f in serazeny)
{
VydajePrase.Add(f);
}
// Příjmy
IEnumerable<Finance> serazeny2 = PrijmyPrase.OrderByDescending(a => a.ID);
PrijmyPrase = new ObservableCollection<Finance>();
foreach (Finance f in serazeny2)
{
PrijmyPrase.Add(f);
}
VyvolejZmenu("VydajePrase");
VyvolejZmenu("PrijmyPrase");
}
#endregion
// **************************************
#region Ovce
/// <summary>
/// Metoda pro práci s ovcí - Přidání, úprava, odebrání nebo změna mladé ovce na matku
/// </summary>
/// <param name="operace">0 - Nová ovce, 1 - Úprava, 2 - Odebrání, 3 - Mladá ovce se stane MATKOU</param>
/// <param name="stav">0 - Jehně, 1 - Dospělá ovce</param>
/// <param name="pohlavi">0 - Žena, 1 - Muž</param>
/// <param name="jmeno">Pojmenování ovce chovatelem</param>
/// <param name="evidencniCislo">Evidenční číslo ovce</param>
/// <param name="datStrihani">Datum posledního stříhání ovce</param>
/// <param name="datZarazeni">Datum zařezení ovce do chovu</param>
/// <param name="datVyrazeni">Datum vyřazení z chovu</param>
/// <param name="datNarozeni">Datum narození</param>
/// <param name="upravovanaOvce">Upravovaná ovce</param>
/// <param name="linie">Linie - rodokmenová</param>
/// <param name="duvodVyrazeni">Dúvod vyřazení z chovu</param>
/// <param name="klasifikace">Kvalita ovce - kvalifikace</param>
/// <param name="popis">Detailnější popis zvířete</param>
/// <param name="matka_cislo">Evidenční číslo matky</param>
/// <param name="otec_cislo">Evidenční číslo otce</param>
/// <param name="mrtvychJehnat">Mrtvých jehňat při porodu</param>
/// <param name="zivychJehnat">Živých jehňat při porodu</param>
/// <param name="odchovJehnat">Odchovaných jehňat</param>
/// <returns></returns>
public bool ZadejOvci(byte operace, byte stav, byte pohlavi, string jmeno, string evidencniCislo,
string datStrihani, string datZarazeni, string datVyrazeni, string datNarozeni,
Ovce upravovanaOvce, string linie, string duvodVyrazeni, string klasifikace,
string popis, string matka_cislo, string otec_cislo, string mrtvychJehnat, string zivychJehnat, string odchovJehnat)
{
// --------------- Pomocné proměnné ---------------
ObservableCollection<Ovce> seznam = new ObservableCollection<Ovce>();
DateTime datumNarozeni_pomocna;
DateTime datumZarazeni_pomocna;
DateTime datumVyrazeni_pomocna;
DateTime datumStrihani_pomocna;
Ovce matka = null;
Ovce otec = null;
int zivychJehnat_pomocna = 0;
int mrtvychJehnat_pomocna = 0;
int odchovanychJehnat_pomocna = 0;
bool odpoved = false;
int zalohaID = 0;
string pomocna = "";
// Mladá ovce
if (stav == 0)
{
zalohaID = ID_Jehne;
seznam = SeznamJehnat;
pomocna = "SeznamJehnat";
}
// Dospelá ovce, beran
else if (stav == 1)
{
// Muž - 1, BERAN
if (pohlavi == 1)
{
zalohaID = ID_Beran;
seznam = SeznamBeranu;
pomocna = "SeznamBeranu";
}
// Žena - 0, OVCE
else if (pohlavi == 0)
{
zalohaID = ID_Ovce;
seznam = SeznamOvci;
pomocna = "SeznamOvci";
}
}
// Přidání nové nebo úprava stávající ovce
if (operace == 0 || operace == 1)
{
// Trimovani a převedení na malá písmena vstupních stringu u ev. čísla, a čísla matky a otce
if (otec_cislo != "")
otec_cislo = otec_cislo.Trim().ToLower();
if (matka_cislo != "")
matka_cislo = matka_cislo.Trim().ToLower();
if (evidencniCislo != "")
evidencniCislo = evidencniCislo.Trim().ToLower();
// Vyhledání konkrétní ovce - nezačíná 0 - tedy jedná o ovci, která je v chovu evidována
// - Ovce, která začíná 0... v evidenčním číslu, není evidována v chovu
// - například se může jednat o novou ovci, která nemá rodiče v chovu, ale je nutné evidovat jejich čísla, proto budou začínat 0
if (!matka_cislo.StartsWith("0") && !otec_cislo.StartsWith("0"))
{
foreach (Ovce o in SeznamOvci)
{
if (o.EvidencniCislo == matka_cislo)
matka = o;
}
foreach (Ovce o in SeznamBeranu)
{
if (o.EvidencniCislo == otec_cislo)
otec = o;
}
}
// Jedná se o ovci, která není v chovu viz. Výše
else
{
matka_cislo = matka_cislo.Remove(0, 1);
otec_cislo = otec_cislo.Remove(0, 1);
matka = new Ovce(matka_cislo);
otec = new Ovce(otec_cislo);
}
// ------------------------------- Ošetření vstupů -------------------------------
// Evidencni cislo
if (evidencniCislo == "")
throw new ArgumentException("Nezadal jsi pořadové číslo");
// Datum narozeni
if (datNarozeni == "")
throw new ArgumentException("Nezadal jsi žádné datum narození");
else
datumNarozeni_pomocna = DateTime.Parse(datNarozeni);
if (datumNarozeni_pomocna > DateTime.Now)
throw new ArgumentException("Zadal jsi datum narození z budoucnosti");
// Datum zarazeni
if (datZarazeni == "")
throw new ArgumentException("Nezadal jsi žádné datum zařazení");
else
datumZarazeni_pomocna = DateTime.Parse(datZarazeni);
// Matka
if (matka_cislo == "")
throw new ArgumentException("Nezadal jsi žádnou matku");
// Otec
if (otec_cislo == "")
throw new ArgumentException("Nezadal jsi žádného otce");
// Pohlavi a stav
if (stav > 1 || stav < 0)
throw new ArgumentException("Nevybral jsi zda se jedna o jehně nebo o dospělou ovci");
if (pohlavi > 1 || pohlavi < 0)
throw new ArgumentException("Nevybral jsi pohlaví ovce.");
// Přidání nové ovce
if (operace == 0)
{
seznam.Add(new Ovce(zalohaID, evidencniCislo, datumNarozeni_pomocna, matka, otec, datumZarazeni_pomocna, stav, pohlavi, popis));
odpoved = true;
if (stav == 0)
ID_Jehne++;
else if (stav == 1)
{
if (pohlavi == 0)
ID_Ovce++;
else if (pohlavi == 1)
ID_Beran++;
}
}
// Úprava stávající
else if (operace == 1)
{
// U kazdeho parametru je kontrola, zda opravdu neco obsahuje, aby se nezapisovalo nic do hodnot
int a = seznam.IndexOf(upravovanaOvce);
seznam[a].DatumNarozeni = datumNarozeni_pomocna;
if (DateTime.TryParse(datStrihani, out datumStrihani_pomocna))
seznam[a].DatumStrihani = datumStrihani_pomocna;
if (DateTime.TryParse(datVyrazeni, out datumVyrazeni_pomocna))
seznam[a].VyrazeniZChovu = datumVyrazeni_pomocna;
if (datZarazeni != "")
seznam[a].ZarazeniDoChovu = datumZarazeni_pomocna;
if (duvodVyrazeni != "")
seznam[a].DuvodVyrazeni = duvodVyrazeni;
if (evidencniCislo != "")
seznam[a].EvidencniCislo = evidencniCislo;
if (jmeno != "")
seznam[a].Jmeno = jmeno;
if (klasifikace != "")
seznam[a].Klasifikace = klasifikace;
if (linie != "")
seznam[a].Linie = linie;
if (int.TryParse(mrtvychJehnat, out mrtvychJehnat_pomocna))
seznam[a].MrtvychJehnat = mrtvychJehnat_pomocna;
if (int.TryParse(odchovJehnat, out odchovanychJehnat_pomocna))
seznam[a].OdchovanychJehnat = odchovanychJehnat_pomocna;
if (int.TryParse(zivychJehnat, out zivychJehnat_pomocna))
seznam[a].ZivychJehnat = zivychJehnat_pomocna;
if (popis != "")
seznam[a].Popis = popis;
seznam[a].Pohlavi = pohlavi;
odpoved = true;
}
}
// Smazani Ovce, Berana, Jehnete
else if (operace == 2)
{
int pomocnaID = 0;
if (stav == 0)
ID_Jehne--;
else if (stav == 1)
{
if (pohlavi == 0)
ID_Ovce--;
else if (pohlavi == 1)
ID_Beran--;
}
pomocnaID = seznam.IndexOf(upravovanaOvce);
seznam.Remove(upravovanaOvce);
foreach (Ovce o in seznam)
{
if (o.ID > pomocnaID)
o.ID--;
}
odpoved = true;
}
// Podminka, pro zmenu jehnete na matku. Lze take zamenit beranka za BERANA
else if (operace == 3)
{
int pomocnaID = SeznamJehnat.IndexOf(upravovanaOvce);
SeznamJehnat.Remove(upravovanaOvce);
ID_Jehne--;
// Validace ID
foreach (Ovce o in SeznamJehnat)
{
if (o.ID > pomocnaID)
o.ID--;
}
// Zařazení do příslusné kolecke - OVCE nebo BERAN
if (upravovanaOvce.Pohlavi == 0)
{
SeznamOvci.Add(upravovanaOvce);
upravovanaOvce.ID = ID_Ovce;
ID_Ovce++;
}
else if (upravovanaOvce.Pohlavi == 1)
{
SeznamBeranu.Add(upravovanaOvce);
upravovanaOvce.ID = ID_Beran;
ID_Beran++;
}
upravovanaOvce.Stav = stav;
odpoved = true;
}
VyvolejZmenu(pomocna);
UlozOvce();
return odpoved;
}
/// <summary>
/// Seřadí kolekci porodů pro OVCE sestupně, tedy poslední nahoře
/// </summary>
public void SeradOvceBeranyJehnata()
{
IEnumerable<Ovce> serazeny = SeznamOvci.OrderByDescending(a => a.ID);
SeznamOvci = new ObservableCollection<Ovce>();
foreach (Ovce f in serazeny)
{
SeznamOvci.Add(f);
}
VyvolejZmenu("SeznamOvci");
IEnumerable<Ovce> serazeny2 = SeznamBeranu.OrderByDescending(a => a.ID);
SeznamBeranu = new ObservableCollection<Ovce>();
foreach (Ovce f in serazeny2)
{
SeznamBeranu.Add(f);
}
VyvolejZmenu("SeznamBeranu");
IEnumerable<Ovce> serazeny3 = SeznamJehnat.OrderByDescending(a => a.ID);
SeznamJehnat = new ObservableCollection<Ovce>();
foreach (Ovce f in serazeny3)
{
SeznamJehnat.Add(f);
}
VyvolejZmenu("SeznamJehnat");
}
/// <summary>
/// Výpočet celkových hodnot narozených, mrtvých a odchovaných selat u OVCE
/// </summary>
/// <param name="operace"></param>
/// <param name="matkaOvce">Ovce pro, kterou se spočte počet jehňat</param>
public void SpoctiPotomkyOvce(byte operace, Ovce matkaOvce)
{
int[] suma_puvodni = new int[3];
suma_puvodni[0] = matkaOvce.ZivychJehnat;
suma_puvodni[1] = matkaOvce.MrtvychJehnat;
suma_puvodni[2] = matkaOvce.OdchovanychJehnat;
int[] suma = new int[3];
// Projdou se všechny záznamy o porodu
foreach (Porod p in PorodyOvce)
{
// Pokud se číslo matky u porodu shoduje s čílem zadané ovce, odečtou se zadané hodnoty
// - Mrtvá, živá a odchovaná jehňata
if (p.MatkaEvidencniCislo == matkaOvce.EvidencniCislo)
{
if (p.Ziva > 0)
suma[0] += p.Ziva;
if (p.Mrtva > 0)
suma[1] += p.Mrtva;
if (p.Odchovana > 0)
suma[2] += p.Odchovana;
}
}
// Pokud se data aktualizovali, nové hodnoty se uloží do atributů dané ovce
if (suma_puvodni[0] != suma[0])
matkaOvce.ZivychJehnat = suma[0];
if (suma_puvodni[1] != suma[1])
matkaOvce.MrtvychJehnat = suma[1];
if (suma_puvodni[2] != suma[2])
matkaOvce.OdchovanychJehnat = suma[2];
// Aktualizace vlastností, aby se data obnovili i na formuláři
matkaOvce.VyvolejZmenu("ZivychJehnat");
matkaOvce.VyvolejZmenu("MrtvychJehnat");
matkaOvce.VyvolejZmenu("OdchovanychJehnat");
}
/// <summary>
/// Vybere jehňata dané ovce podle evidenčního čísla
/// </summary>
/// <param name="evidencniCislo">Evidencni cislo matky, pro kterou se hledaji jehnata</param>
/// <returns></returns>
public ObservableCollection<Ovce> VyberJehnata(string evidencniCislo)
{
ObservableCollection<Ovce> nalezene = new ObservableCollection<Ovce>();
foreach (Ovce o in SeznamJehnat)
{
if (o.Matka.EvidencniCislo == evidencniCislo)
nalezene.Add(o);
}
return nalezene;
}
#endregion
// **************************************
#region Prase
/// <summary>
/// Metoda pro přidání / úpravu PRASETE uloženého v kolekci SEZNAM SELAT
/// </summary>
/// <param name="jmeno">Pojmenování chovatele</param>
/// <param name="vaha">Váha prasete v KG</param>
/// <param name="popis">Detailnější popis kusu</param>
/// <param name="zena">Žena</param>
/// <param name="muz">Muž</param>
/// <param name="maruska">První prasnice - matka</param>
/// <param name="baruska">Druhá prasnice - matka</param>
/// <param name="datumNarozeni">Datum narození selete</param>
/// <param name="upravovaneSele">Upravované sele</param>
public void ZadejSele(string jmeno, string vaha, string popis, bool? zena, bool? muz, bool? maruska, bool? baruska, string datumNarozeni, Prase upravovaneSele)
{
// Pomocné proměnné
DateTime datumNarozeni_pomocna;
int vaha_pomocna = 0;
string pohlavi = "Nezadané";
Svine matka_pomocna = null;
// Ošetření vstupu
if (maruska == null && baruska == null)
throw new ArgumentException("Nezadal jsi žádnou matku!");
if (datumNarozeni == "")
throw new ArgumentException("Nezadal jsi žádné datum narození!");
else
datumNarozeni_pomocna = DateTime.Parse(datumNarozeni);
if (datumNarozeni_pomocna > DateTime.Now)
throw new ArgumentException("Zadal jsi datum narození z budoucnosti");
if (maruska == true)
matka_pomocna = Maruska;
else if (baruska == true)
matka_pomocna = Baruska;
if (muz == true)
pohlavi = "Muž";
else if (zena == true)
pohlavi = "Žena";
if (vaha != "")
vaha_pomocna = int.Parse(vaha);
if (popis == "")
popis = "Žádný";
// Přídání nového prasete do kolekce
if (upravovaneSele == null)
{
SeznamSelat.Add(new Prase(ID_Sele, datumNarozeni_pomocna, matka_pomocna));
Trid();
ID_Sele++;
}
// Úprava stávajícího prasete
else
{
int pomocna = SeznamSelat.IndexOf(upravovaneSele);
SeznamSelat[pomocna].DatumNarozeni = datumNarozeni_pomocna;
SeznamSelat[pomocna].Pohlavi = pohlavi;
SeznamSelat[pomocna].Matka = matka_pomocna;
SeznamSelat[pomocna].Popis = popis;
SeznamSelat[pomocna].Jmeno = jmeno;
SeznamSelat[pomocna].Vaha = vaha_pomocna;
}
UlozPrase();
}
/// <summary>
/// Selata se rozdělí do dvou kolekcí - SeleMaruska a SeleBaruska - tedy podle své matky
/// </summary>
public void Trid()
{
// Volání pomocné metody, která provede samotné třídění
Roztrid(1);
Roztrid(2);
VyvolejZmenu("SeleMaruska");
VyvolejZmenu("SeleBaruska");
}
/// <summary>
/// Roztřídění selátek k matkám, podle zadaného čísla matky
/// </summary>
/// <param name="matka">1 - Maruška, 2 - Baruška</param>
/// <returns></returns>
private void Roztrid(int matka)
{
ObservableCollection<Prase> zalozniList = new ObservableCollection<Prase>();
// První prasnice - pojmenovaná MARUSKA
if (matka == 1)
{
foreach (Prase p in SeznamSelat)
{
if (p.Matka.Jmeno == "Maruska")
zalozniList.Add(p);
}
SeleMaruska = zalozniList;
}
// Druhá prasnice - pojmenovaná BARUSKA
else if (matka == 2)
{
foreach (Prase p in SeznamSelat)
{
if (p.Matka.Jmeno == "Baruska")
zalozniList.Add(p);
}
SeleBaruska = zalozniList;
}
}
/// <summary>
/// Metoda pro odebrání prase z kolekce SEZNAM SELAT
/// </summary>
/// <param name="prase">Prase, které bude odebráno</param>
public void OdeberPrase(Prase prase)
{
int id = prase.EvidencniCislo;
SeznamSelat.Remove(prase);
foreach (Prase p in SeznamSelat)
{
if (p.EvidencniCislo > id)
p.EvidencniCislo--;
}
ID_Sele--;
Trid();
UlozPrase();
}
/// <summary>
/// Vytvoří více prasat současně, například při porodu - ukládáno do kolekce SEZNAM SELAT
/// </summary>
/// <param name="pocet">Počet prasat</param>
/// <param name="datumNarozeni">Datum narození prasat</param>
/// <param name="matka">Prasnice, která je matkou</param>
public void GenerujSelata(int pocet, DateTime datumNarozeni, Svine matka)
{
// + 2 protoze Svine maji cislo 1 a 2
int pomocna = (SeznamSelat.Count) + 2;
// Ošetření vstupů
if (matka == null)
throw new ArgumentException("Nezadal jsi matku!!");
if (datumNarozeni > DateTime.Now)
throw new ArgumentException("Zadal jsi datum z budoucnosti");
if (pocet <= 0)
throw new ArgumentException("Nezadal jsi žádná selátka");
for (int i = 0; i < pocet; i++)
{
// Přidání selátek do kolekce
SeznamSelat.Add(new Prase(i + pomocna, datumNarozeni, matka));
ID_Sele++;
}
Trid();
UlozPrase();
}
/// <summary>
/// Výpočet celkových hodnot narozených, mrtvých a odchovaných selat u PRASNICE
/// </summary>
/// <param name="matka">Jedna je dvou PRASNIC</param>
public void SpoctiPotomkyPrase(Svine matka)
{
// pomocné proměnné
int[] suma_puvodni = new int[3];
suma_puvodni[0] = matka.PocetSelat_zivych;
suma_puvodni[1] = matka.PocetSelat_mrtvych;
suma_puvodni[2] = matka.PocerSelat_odchovanych;
int[] suma = new int[3];
// Projdou se porody dané PRASNICE a u každého se zaznamená počet živých, mrtvých a odchovaných selat pro výpočet CELKEM
foreach (Porod p in PorodyPrase)
{
// Jméno prasnice se shoduje s hledanou
if (p.Matka.Jmeno == matka.Jmeno)
{
if (p.Ziva > 0)
suma[0] += p.Ziva;
if (p.Mrtva > 0)
suma[1] += p.Mrtva;
if (p.Odchovana > 0)
suma[2] += p.Odchovana;
}
}
// Data se změnila, tedy je nutné je upravit na aktuální hodnotu
if (suma_puvodni[0] != suma[0])
matka.PocetSelat_zivych = suma[0];
if (suma_puvodni[1] != suma[1])
matka.PocetSelat_mrtvych = suma[1];
if (suma_puvodni[2] != suma[2])
matka.PocerSelat_odchovanych = suma[2];
// vyvolání změny pro aktualizaci dat na formuláři
matka.VyvolejZmenu("PocetSelat_zivych");
matka.VyvolejZmenu("PocetSelat_mrtvych");
matka.VyvolejZmenu("PocerSelat_odchovanych");
}
#endregion
// **************************************
#region Porod
/// <summary>
/// Zadání záznamu o porodu zvířete (Ovce nebo Prase)
/// </summary>
/// <param name="druhZvire">0 - prase, 1 - ovce</param>
/// <param name="konkZvire">0 - maruska, 1 - baruska</param>
/// <param name="operace">0 - nový, 1 - úprava, 2 - odebrání</param>
/// <param name="ziva">Počet živých selat</param>
/// <param name="mrtva">Mrtvá selata při porodu</param>
/// <param name="odchov">Odchovaných selat</param>
/// <param name="prubPorod">Popis průběhu porodu</param>
/// <param name="kontrolBrezost">Kontrola zda je březí</param>
/// <param name="datumTestuBrezost">Datum testu březosti</param>
/// <param name="datZapus">Datum zapuštění</param>
/// <param name="datNaroz">Datum skutečného narození selat</param>
/// <param name="evidencniCisloOvce">Evidencni cislo ovce</param>
public bool ZadejPorod(byte druhZvire, byte konkZvire, byte operace, string evidencniCisloOvce, Porod zaznam, string ziva, string mrtva, string odchov, string prubPorod, bool kontrolBrezost, string datumTestuBrezost,
string datZapus, string mesicNarozeni, string datNaroz)
{
bool odpoved = false;
ObservableCollection<Porod> seznam = new ObservableCollection<Porod>();
Svine matka = null;
// Pomocné proměnné
int zivaPomocna = 0;
int mrtvaPomocna = 0;
int odchovPomocna = 0;
DateTime datumzapusteni_pomocna;
DateTime datumNarozeni_pomocna;
// Nastavení požadované kolekce a u prasete konkrétní PRASNICE
// PRASE
if (druhZvire == 0)
{
seznam = PorodyPrase;
if (konkZvire == 0)
matka = Maruska;
else
matka = Baruska;
}
// OVCE
else if (druhZvire == 1)
{
seznam = PorodyOvce;
}
// Parsovani počtu selat
if (ziva != "")
zivaPomocna = int.Parse(ziva);
if (mrtva != "")
mrtvaPomocna = int.Parse(mrtva);
if (odchov != "")
odchovPomocna = int.Parse(odchov);
// Kontrola hodnot v selatkach
if (zivaPomocna < 0 || mrtvaPomocna < 0 || odchovPomocna < 0)
throw new ArgumentException("Zadal jsi zápornou hodnotu do selátek");
// OVCE
if (druhZvire == 1)
{
// Přidání nového nebo úprava stávajícího záznamu
if (operace == 0 || operace == 1)
{
// Pomocné proměnné
int mesicNarozeni_pomocna;
int mesicZapusteni_pomocna;
DateTime datumNarozeni_pomocna_ovce;
// Ošetření vyjímek
if (mesicNarozeni == "")
throw new ArgumentException("Nezadal jsi žádný předpokládáný měsíc narozeni jehňat.");
else
mesicNarozeni_pomocna = int.Parse(mesicNarozeni);
if (datZapus == "")
throw new ArgumentException("Nezadal jsi žádný měsíc vpuštění beranu do ohrady");
else
mesicZapusteni_pomocna = int.Parse(datZapus);
// Nový záznam
if (operace == 0)
{
seznam.Add(new Porod(ID_Porod_Ovce, evidencniCisloOvce, mesicZapusteni_pomocna, mesicNarozeni_pomocna));
VyvolejZmenu("PorodyOvce");
ID_Porod_Ovce++;
UlozPorody();
UlozID();
odpoved = true;
}
// Úprava stávajícího
else if (operace == 1)
{
int a = seznam.IndexOf(zaznam);
if (datNaroz != "")
{
datumNarozeni_pomocna_ovce = DateTime.Parse(datNaroz);
seznam[a].DatumNarozeni = datumNarozeni_pomocna_ovce;
}
seznam[a].MesicPorodu = mesicNarozeni_pomocna;
seznam[a].MesicVpusteniBerana = mesicZapusteni_pomocna;
seznam[a].Ziva = zivaPomocna;
seznam[a].Mrtva = mrtvaPomocna;
seznam[a].Odchovana = odchovPomocna;
seznam[a].PrubehPorodu = prubPorod;
VyvolejZmenu("PorodyOvce");
UlozPorody();
odpoved = true;
}
}
// Odebrání záznamu
else if (operace == 2)
{
int id = zaznam.ID;
if (zaznam != null)
seznam.Remove(zaznam);
foreach (Porod p in seznam)
{
if (p.ID > id)
p.ID--;
}
// Snizeni budouciho ID, protoze jedno ID v seznamu ubylo
ID_Porod_Ovce--;
VyvolejZmenu("PorodyOvce");
UlozPorody();
UlozID();
odpoved = true;
}
}
// PRASE
if (operace == 0 && druhZvire == 0)
{
// Ošetření vstupu
if (datZapus == "")
throw new ArgumentException("Nezadal jsi žádné datum zapuštění");
else
datumzapusteni_pomocna = DateTime.Parse(datZapus);
seznam.Add(new Porod(ID_Porod_Prase, matka, datumzapusteni_pomocna));
VyvolejZmenu("PorodyPrase");
ID_Porod_Prase++;
UlozPorody();
UlozID();
odpoved = true;
}
// Uprava stavajiciho zaznamu PRASE
else if (operace == 1 && druhZvire == 0)
{
int a = PorodyPrase.IndexOf(zaznam);
// Zapusteni
if (datZapus == "")
throw new ArgumentException("Nezadal jsi žádné datum zapuštění");
else
datumzapusteni_pomocna = DateTime.Parse(datZapus);
// Datum narozeni
if (datNaroz != "")
{
DateTime.TryParse(datNaroz, out datumNarozeni_pomocna);
seznam[a].DatumNarozeni = datumNarozeni_pomocna;
}
seznam[a].DatumZapusteni = datumzapusteni_pomocna;
seznam[a].KontrolaBrezosti = kontrolBrezost;
seznam[a].Mrtva = mrtvaPomocna;
seznam[a].Ziva = zivaPomocna;
seznam[a].Odchovana = odchovPomocna;
seznam[a].PrubehPorodu = prubPorod;
VyvolejZmenu("PorodyPrase");
UlozPorody();
odpoved = true;
}
// Odebrani zaznamu PRASE
else if (operace == 2)
{
int id = zaznam.ID;
seznam.Remove(zaznam);
// Snizeni vsech ID nad smazanym
foreach (Porod p in seznam)
{
if (p.ID > id)
p.ID--;
}
// Snizeni budouciho ID, protoze jedno ID v seznamu ubylo
ID_Porod_Prase--;
VyvolejZmenu("PorodyPrase");
UlozPorody();
UlozID();
odpoved = true;
}
return odpoved;
}
/// <summary>
/// Seřadí kolekci porodů PRASE sestupně, tedy poslední nahoře
/// </summary>
public void SeradPorodyPrase()
{
IEnumerable<Porod> serazeny = PorodyPrase.OrderByDescending(a => a.ID);
PorodyPrase = new ObservableCollection<Porod>();
foreach (Porod f in serazeny)
{
PorodyPrase.Add(f);
}
VyvolejZmenu("PorodyPrase");
}
/// <summary>
/// Vybere pro zadanou PRASNICI porody, aby bylo možné je zobrazit v daném ListBoxu
/// </summary>
/// <param name="sv">Prasnice pro kterou budou porody vybírány</param>
/// <returns></returns>
public ObservableCollection<Porod> VyberPorodyPrase(Svine sv)
{
string jmeno = "";
ObservableCollection<Porod> seznamVybranych = new ObservableCollection<Porod>();
if (sv.Jmeno == "Maruska")
jmeno = "Maruska";
else if (sv.Jmeno == "Baruska")
jmeno = "Baruska";
if (PorodyPrase.Count > 0)
{
foreach (Porod p in PorodyPrase)
{
if (p.Matka.Jmeno == jmeno)
seznamVybranych.Add(p);
}
}
return seznamVybranych;
}
/// <summary>
/// Vyhledani konkretnich porodu pro jednu z ovci
/// </summary>
/// <param name="evidencniCislo">Evidencni cislo ovce</param>
/// <returns></returns>
public ObservableCollection<Porod> VyberPorodyOvce(string evidencniCislo)
{
ObservableCollection<Porod> nalezene = new ObservableCollection<Porod>();
foreach (Porod p in PorodyOvce)
{
if (p.MatkaEvidencniCislo == evidencniCislo)
nalezene.Add(p);
}
return nalezene;
}
#endregion
// **************************************
#region Ockovani a odcerveni
/// <summary>
/// Slouzi pro pridani, upravu a odebrani zaznamu z evidence o ockovani nebo odcerveni
/// </summary>
/// <param name="volba">0 - Ockovani, 1 - Odcerveni</param>
/// <param name="operace">0 - Novy zaznam, 1 - Uprava, 2 - Odebrani</param>
/// <param name="evidencniCislo">Evidencni cislo vztazne ovce</param>
/// <param name="datum">Datum ukonu</param>
/// <param name="pripravek">Podany pripravek</param>
/// <param name="ucel">Ucel ockovani / odcerveni </param>
/// <param name="popis">Doplnujici popis</param>
/// <param name="cena">Castka v CZK</param>
/// <returns>Odpověď, zda se proces podařil</returns>
public bool ZadejOckovaniOdcerveni(byte volba, byte operace, string evidencniCislo, string datum, string pripravek, string ucel, string popis, string cena, Ockovani zaznamOckovani, Odcerveni zaznamOdcerveni)
{
bool odpoved = false;
int cena_pomocna = 0;
DateTime datum_pomocna = DateTime.Now;
// Nový záznam nebo úprava stávajícího
if (operace != 2)
{
// --------------------------- Ošetření vstupů ---------------------------
// Popis
if (popis == "")
popis = "Žádný";
// Ucel
if (ucel == "")
ucel = "Nezadáno";
// Pripravek
if (pripravek == "")
throw new ArgumentException("Nezadal jsi podaný přípravek");
// Cena
if (cena == "")
throw new ArgumentException("Nezadal jsi cenu.");
else
cena_pomocna = int.Parse(cena);
if (cena_pomocna < 0)
throw new ArgumentException("Zadaná cena je menší než 0. Uprav ji minimálně na 0");
// Datum
if (datum == "")
throw new ArgumentException("Nezadal jsi datum provedeného očkování / odčervení");
else
datum_pomocna = DateTime.Parse(datum);
if (datum_pomocna > DateTime.Now)
throw new ArgumentException("Zadané datum je z budoucnosti. Zkontroluj zadání");
}
// --------------------------- Očkování ---------------------------
if (volba == 0)
{
// Nový záznam
if (operace == 0)
{
SeznamOckovani.Add(new Ockovani(ID_Ockovani, datum_pomocna, evidencniCislo, pripravek, ucel, popis, cena_pomocna));
ID_Ockovani++;
VyvolejZmenu("SeznamOckovani");
odpoved = true;
UlozOckovani();
UlozID();
}
// Úprava stávajícího
else if (operace == 1 && zaznamOckovani != null)
{
int a = SeznamOckovani.IndexOf(zaznamOckovani);
SeznamOckovani[a].Datum = datum_pomocna;
SeznamOckovani[a].Cena = cena_pomocna;
SeznamOckovani[a].Popis = popis;
SeznamOckovani[a].Pripravek = pripravek;
SeznamOckovani[a].Ucel = ucel;
VyvolejZmenu("SeznamOckovani");
odpoved = true;
UlozOckovani();
}
// Odebrání záznamu
else if (operace == 2 && zaznamOckovani != null)
{
int zalohaID = zaznamOckovani.ID;
if (zaznamOckovani != null)
SeznamOckovani.Remove(zaznamOckovani);
foreach (Ockovani o in SeznamOckovani)
{
if (o.ID > zalohaID)
o.ID--;
}
ID_Ockovani--;
VyvolejZmenu("SeznamOckovani");
odpoved = true;
UlozOckovani();
UlozID();
}
}
// --------------------------- Odčervení ---------------------------
else if (volba == 1)
{
// Nový záznam
if (operace == 0)
{
SeznamOdcerveni.Add(new Odcerveni(ID_Odcerveni, datum_pomocna, evidencniCislo, pripravek, ucel, popis, cena_pomocna));
ID_Odcerveni++;
VyvolejZmenu("SeznamOdcerveni");
odpoved = true;
UlozOdcerveni();
UlozID();
}
// Úprava stávajícího
else if (operace == 1 && zaznamOdcerveni != null)
{
int a = SeznamOdcerveni.IndexOf(zaznamOdcerveni);
SeznamOdcerveni[a].Datum = datum_pomocna;
SeznamOdcerveni[a].Cena = cena_pomocna;
SeznamOdcerveni[a].Popis = popis;
SeznamOdcerveni[a].Pripravek = pripravek;
SeznamOdcerveni[a].Ucel = ucel;
VyvolejZmenu("SeznamOdcerveni");
odpoved = true;
UlozOdcerveni();
}
// Odebrání záznamu
else if (operace == 2 && zaznamOdcerveni != null)
{
int zalohaID = zaznamOdcerveni.ID;
if (SeznamOdcerveni != null)
SeznamOdcerveni.Remove(zaznamOdcerveni);
foreach (Odcerveni o in SeznamOdcerveni)
{
if (o.ID > zalohaID)
o.ID--;
}
ID_Odcerveni--;
VyvolejZmenu("SeznamOdcerveni");
odpoved = true;
UlozOdcerveni();
UlozID();
}
}
return odpoved;
}
/// <summary>
/// Vybere očkování pro konkrétní OVCI
/// </summary>
/// <param name="evCislo">Evidenční číslo dané ovce</param>
/// <returns></returns>
public ObservableCollection<Ockovani> VyberOckovani(string evCislo)
{
ObservableCollection<Ockovani> nalezene = new ObservableCollection<Ockovani>();
if (SeznamOckovani.Count > 0)
{
foreach (Ockovani o in SeznamOckovani)
{
if (o.EvidencniCisloOvce == evCislo)
nalezene.Add(o);
}
}
return nalezene;
}
/// <summary>
/// Vybere odčervení pro konkrétní OVCI
/// </summary>
/// <param name="evCislo">Evidenční číslo dané ovce</param>
/// <returns></returns>
public ObservableCollection<Odcerveni> VyberOdcerveni(string evCislo)
{
ObservableCollection<Odcerveni> nalezene = new ObservableCollection<Odcerveni>();
if (SeznamOdcerveni.Count > 0)
{
foreach (Odcerveni o in SeznamOdcerveni)
{
if (o.EvidencniCisloOvce == evCislo)
nalezene.Add(o);
}
}
return nalezene;
}
#endregion
// **************************************
#region Veterina
/// <summary>
/// Přídání nebo úprava veterinárních záznamů - kolekce SeznamVeterinarnichZaznamu_Prase * Ovce
/// </summary>
/// <param name="sele">Vztažné sele</param>
/// <param name="vet">Při úpravě stávajícího záznamu</param>
/// <param name="ucel">Účel veterinární návštevy</param>
/// <param name="ukony">Veterinární úkony</param>
/// <param name="datum">Datum návštevy veterináře</param>
/// <param name="leky">Podané léčivo</param>
/// <param name="cislo">Číslo veterinární návštevy</param>
/// <param name="cena">Cena zákroku</param>
/// <param name="ukon">0 - nový záznam, 1 - úprava záznamu</param>
public void ZadejVeterinarniZaznam(Prase sele, Ovce ovce, Veterina vet, string ucel, string ukony, string datum, string leky, string cena, byte ukon)
{
ObservableCollection<Veterina> seznam;
// Výběr kolekce, do které bude uloženo - Ovce nebo Prase
if (sele != null)
seznam = SeznamVeterinarnichZaznamu_Prase;
else
seznam = SeznamVeterinarnichZaznamu_Ovce;
// Pomocné proměnné
DateTime datum_pomocna;
int cena_pomocna;
// Ošetření vstupu, pomocí vyvolání vyjímek se zprávou pro uživatele
if (ukony == "")
ukony = "Žádné";
if (leky == "")
leky = "Žádné";
if (ucel == "")
throw new ArgumentException("Nezadal jsi žádný účel návštavy veterináře");
if (datum == "")
throw new ArgumentException("Nezadal jsi žádné datum");
else
datum_pomocna = DateTime.Parse(datum);
if (cena == "")
throw new ArgumentException("Nezadal jsi žádnou cenu zákroku");
else
cena_pomocna = int.Parse(cena);
if (cena_pomocna < 0)
throw new ArgumentException("Zadal jsi zápornou cenu");
// Nový veterinární záznam
if (ukon == 0)
{
// Zadava se veterinarni zaznam pro PRASE
if (ovce == null)
{
seznam.Add(new Veterina(ucel, ukony, datum_pomocna, leky, sele, null, ID_Veterina_Prase, cena_pomocna));
ID_Veterina_Prase++;
}
// Zadava se veterinarni zaznam pro OVCI
else
{
seznam.Add(new Veterina(ucel, ukony, datum_pomocna, leky, null, ovce, ID_Veterina_Ovce, cena_pomocna));
ID_Veterina_Ovce++;
}
}
// Uprava stavajiciho veterinarniho zaznamu
else if (ukon == 1)
{
int a = seznam.IndexOf(vet);
seznam[a].PodaneLecivo = vet.PodaneLecivo;
seznam[a].Ucel = vet.Ucel;
seznam[a].DatumNavstevy = vet.DatumNavstevy;
seznam[a].ProvedeneUkony = vet.ProvedeneUkony;
seznam[a].Cena = vet.Cena;
seznam[a].CisloNavstevy = vet.CisloNavstevy;
VyvolejZmenu("SeznamVeterinarnichZaznamu_Prase");
VyvolejZmenu("SeznamVeterinarnichZaznamu_Ovce");
}
UlozVeterina();
VyvolejZmenu("SeznamVeterinarnichZaznamu_Prase");
VyvolejZmenu("SeznamVeterinarnichZaznamu_Ovce");
}
/// <summary>
/// Pro zadané zvíře (Ovce nebo Prase) vybere VETERINÁRNÍ ZÁZNAMY
/// </summary>
/// <param name="sele">Prase pro které se vyhledají veterinární záznamy</param>
/// <param name="ovce">Ovce pro kterou se vyhledají veterinární záznamy</param>
/// <returns></returns>
public ObservableCollection<Veterina> VyberZaznamy(Prase sele, Ovce ovce)
{
// Kolekce pro nalezené záznamy
ObservableCollection<Veterina> nalezene = new ObservableCollection<Veterina>();
// Záznamy prase
if (sele != null)
{
foreach (Veterina v in SeznamVeterinarnichZaznamu_Prase)
{
if (v.VztaznePrase.EvidencniCislo == sele.EvidencniCislo)
{
nalezene.Add(v);
}
}
if (nalezene != null)
{
ZaznamySelete = nalezene;
VyvolejZmenu("ZaznamySelete");
}
}
// Záznamy ovce
else if (ovce != null)
{
foreach (Veterina v in SeznamVeterinarnichZaznamu_Ovce)
{
if (v.VztaznaOvce.EvidencniCislo == ovce.EvidencniCislo)
{
nalezene.Add(v);
}
}
}
return nalezene;
}
#endregion
// **************************************
#region Save / Load
/// <summary>
/// Ulozeni vydaju pro dane zvire
/// </summary>
/// <param name="a">0 - Prase, 1 - Ovce</param>
public void UlozVydaje(byte a)
{
// Pomocná kolekce
ObservableCollection<Finance> Vydaje = new ObservableCollection<Finance>();
string cestaVydaje = "";
// OVCE
if (a == 1)
{
Vydaje = VydajeOvce;
cestaVydaje = cestaVydajeOvce;
}
// PRASE
else if (a == 0)
{
Vydaje = VydajePrase;
cestaVydaje = cestaVydajePrase;
}
// Instance serializéru
XmlSerializer serializer = new XmlSerializer(Vydaje.GetType());
// Projde se kolekce a uloží se v XML do souboru
using (StreamWriter sr = new StreamWriter(cestaVydaje))
{
serializer.Serialize(sr, Vydaje);
}
}
/// <summary>
/// Nacteni prijmu
/// </summary>
/// <param name="a">0 - Prase, 1 - Ovce</param>
public void NactiPrijmy(byte a)
{
// Pomocná kolekce
ObservableCollection<Finance> Prijem = new ObservableCollection<Finance>();
string cestaPrijmy = "";
// OVCE
if (a == 1)
{
cestaPrijmy = cestaPrijmyOvce;
}
// PRASE
else if (a == 0)
{
cestaPrijmy = cestaPrijmyPrase;
}
// Instance serializéru
XmlSerializer serializer = new XmlSerializer(Prijem.GetType());
if (File.Exists(cestaPrijmy))
{
// Projde se XML a rozdělí se na jednotlivé objekty a ty se uloží do kolekce
using (StreamReader sr = new StreamReader(cestaPrijmy))
{
Prijem = (ObservableCollection<Finance>)serializer.Deserialize(sr);
}
}
else
Prijem = new ObservableCollection<Finance>();
if (a == 0)
PrijmyPrase = Prijem;
else if (a == 1)
PrijmyOvce = Prijem;
}
/// <summary>
/// Nacteni vydaju
/// </summary>
/// <param name="a">0 - Prase, 1 - Ovce</param>
public void NactiVydaje(byte a)
{
ObservableCollection<Finance> Vydaje = new ObservableCollection<Finance>();
string cestaVydaje = "";
if (a == 1)
{
cestaVydaje = cestaVydajeOvce;
}
else if (a == 0)
{
cestaVydaje = cestaVydajePrase;
}
XmlSerializer serializer = new XmlSerializer(Vydaje.GetType());
if (File.Exists(cestaVydaje))
{
using (StreamReader sr = new StreamReader(cestaVydaje))
{
Vydaje = (ObservableCollection<Finance>)serializer.Deserialize(sr);
}
}
else
Vydaje = new ObservableCollection<Finance>();
if (a == 0)
VydajePrase = Vydaje;
else if (a == 1)
VydajeOvce = Vydaje;
}
/// <summary>
/// Uložení prijmy pro dane zvire
/// </summary>
/// <param name="a">0 - Prase, 1 - Ovce</param>
public void UlozPrijmy(byte a)
{
// Pomocná kolekce
ObservableCollection<Finance> Prijem = new ObservableCollection<Finance>();
string cestaPrijmy = "";
// OVCE
if (a == 1)
{
Prijem = PrijmyOvce;
cestaPrijmy = cestaPrijmyOvce;
}
// PRASE
else if (a == 0)
{
Prijem = PrijmyPrase;
cestaPrijmy = cestaPrijmyPrase;
}
// instance serializéru
XmlSerializer serializer = new XmlSerializer(Prijem.GetType());
// Projde se kolekce a uloží se v XML do souboru
using (StreamWriter sr = new StreamWriter(cestaPrijmy))
{
serializer.Serialize(sr, Prijem);
}
}
/// <summary>
/// Uložení všech ovcí - kolekce jehňat, ovcí a beranů
/// </summary>
public void UlozOvce()
{
XmlSerializer serializer = new XmlSerializer(SeznamOvci.GetType());
using (StreamWriter sw = new StreamWriter(cestaOvce))
{
serializer.Serialize(sw, SeznamOvci);
}
using(StreamWriter sw = new StreamWriter(cestaJehnata))
{
serializer.Serialize(sw, SeznamJehnat);
}
using (StreamWriter sw = new StreamWriter(cestaBerani))
{
serializer.Serialize(sw, SeznamBeranu);
}
}
/// <summary>
/// Načtení dat pro kolekci jehňat, beranů a ovcí
/// </summary>
public void NactiOvce()
{
XmlSerializer serializer = new XmlSerializer(SeznamOvci.GetType());
if (File.Exists(cestaOvce))
{
using (StreamReader sr = new StreamReader(cestaOvce))
{
SeznamOvci = (ObservableCollection<Ovce>)serializer.Deserialize(sr);
}
}
else
SeznamOvci = new ObservableCollection<Ovce>();
if (File.Exists(cestaBerani))
{
using (StreamReader sr = new StreamReader(cestaBerani))
{
SeznamBeranu = (ObservableCollection<Ovce>)serializer.Deserialize(sr);
}
}
else
SeznamBeranu = new ObservableCollection<Ovce>();
if (File.Exists(cestaJehnata))
{
using (StreamReader sr = new StreamReader(cestaJehnata))
{
SeznamJehnat = (ObservableCollection<Ovce>)serializer.Deserialize(sr);
}
}
else
SeznamJehnat = new ObservableCollection<Ovce>();
}
/// <summary>
/// Uložení všech záznamů očkování - kolekce SeznamOckovani
/// </summary>
public void UlozOckovani()
{
XmlSerializer serializer = new XmlSerializer(SeznamOckovani.GetType());
using (StreamWriter sw = new StreamWriter(cestaOckovani))
{
serializer.Serialize(sw, SeznamOckovani);
}
}
/// <summary>
/// Načtení všech záznamů o očkování - kolekce SeznamOckovani
/// </summary>
public void NactiOckovani()
{
XmlSerializer serializer = new XmlSerializer(SeznamOckovani.GetType());
if (File.Exists(cestaOckovani))
{
using (StreamReader sr = new StreamReader(cestaOckovani))
{
SeznamOckovani = (ObservableCollection<Ockovani>)serializer.Deserialize(sr);
}
}
else
SeznamOckovani = new ObservableCollection<Ockovani>();
}
/// <summary>
/// Uložení všech záznamů o odčervení - kolekce SeznamOdcerveni
/// </summary>
public void UlozOdcerveni()
{
XmlSerializer serializer = new XmlSerializer(SeznamOdcerveni.GetType());
using (StreamWriter sw = new StreamWriter(cestaOdcerveni))
{
serializer.Serialize(sw, SeznamOdcerveni);
}
}
/// <summary>
/// Načtení všech záznamů o odčervení - kolekce SeznamOdcerveni
/// </summary>
public void NactiOdcerveni()
{
XmlSerializer serializer = new XmlSerializer(SeznamOdcerveni.GetType());
if (File.Exists(cestaOdcerveni))
{
using (StreamReader sr = new StreamReader(cestaOdcerveni))
{
SeznamOdcerveni = (ObservableCollection<Odcerveni>)serializer.Deserialize(sr);
}
}
else
SeznamOdcerveni = new ObservableCollection<Odcerveni>();
}
/// <summary>
/// Uložení všech porodů Ovce i Prase - kolekce PorodyPrase, PorodyOVce
/// </summary>
public void UlozPorody()
{
XmlSerializer serializer = new XmlSerializer(PorodyPrase.GetType());
using (StreamWriter sw = new StreamWriter(cestaPorodyPrase))
{
serializer.Serialize(sw, PorodyPrase);
}
using (StreamWriter sw = new StreamWriter(cestaPorodyOvce))
{
serializer.Serialize(sw, PorodyOvce);
}
}
/// <summary>
/// Načtení všech porodů Ovce i Prase - kolekce PorodyPrase, PorodyOvce
/// </summary>
public void NactiPorody()
{
XmlSerializer serializer = new XmlSerializer(PorodyPrase.GetType());
if (File.Exists(cestaPorodyPrase))
{
using (StreamReader sr = new StreamReader(cestaPorodyPrase))
{
PorodyPrase = (ObservableCollection<Porod>)serializer.Deserialize(sr);
}
}
else
PorodyPrase = new ObservableCollection<Porod>();
if (File.Exists(cestaPorodyOvce))
{
using (StreamReader sr = new StreamReader(cestaPorodyOvce))
{
PorodyOvce = (ObservableCollection<Porod>)serializer.Deserialize(sr);
}
}
else
PorodyOvce = new ObservableCollection<Porod>();
}
/// <summary>
/// Uložení všech ID, které identifikují všechny prvky v kolekcích
/// </summary>
public void UlozID()
{
List<int> ids = new List<int>();
ids.Add(ID_Finance_Prase);
ids.Add(ID_Ovce);
ids.Add(ID_Porod_Prase);
ids.Add(ID_Sele);
ids.Add(ID_Veterina_Prase);
ids.Add(ID_Beran);
ids.Add(ID_Jehne);
ids.Add(ID_Finance_Ovce);
ids.Add(ID_Veterina_Ovce);
ids.Add(ID_Odcerveni);
ids.Add(ID_Ockovani);
ids.Add(ID_Porod_Ovce);
XmlSerializer serializer = new XmlSerializer(ids.GetType());
using (StreamWriter sw = new StreamWriter(cestaID))
{
serializer.Serialize(sw, ids);
}
}
/// <summary>
/// Načtení všech IDs
/// </summary>
public void NactiID()
{
List<int> ids = new List<int>();
XmlSerializer serializer = new XmlSerializer(ids.GetType());
if (File.Exists(cestaID))
{
using (StreamReader sr = new StreamReader(cestaID))
{
ids = (List<int>)serializer.Deserialize(sr);
}
}
else
ids = new List<int>();
ID_Finance_Prase = ids[0];
ID_Ovce = ids[1];
ID_Porod_Prase = ids[2];
ID_Sele = ids[3];
ID_Veterina_Prase = ids[4];
ID_Beran = ids[5];
ID_Jehne = ids[6];
ID_Finance_Ovce = ids[7];
ID_Veterina_Ovce = ids[8];
ID_Odcerveni = ids[9];
ID_Ockovani = ids[10];
ID_Porod_Ovce = ids[11];
}
/// <summary>
/// Uložení všech selat, od obou prasnic - kolekce SeznamSelat
/// </summary>
public void UlozPrase()
{
XmlSerializer serializer = new XmlSerializer(SeznamSelat.GetType());
using (StreamWriter sw = new StreamWriter(cestaPrase))
{
serializer.Serialize(sw, SeznamSelat);
}
}
/// <summary>
/// Načtení všech selat, od obou prasnic - kolekce SeznamSelat
/// </summary>
public void NactiPrase()
{
XmlSerializer serializer = new XmlSerializer(SeznamSelat.GetType());
if (File.Exists(cestaPrase))
{
using (StreamReader sr = new StreamReader(cestaPrase))
{
SeznamSelat = (ObservableCollection<Prase>)serializer.Deserialize(sr);
}
}
else
SeznamSelat = new ObservableCollection<Prase>();
}
/// <summary>
/// Uložení všech veterinárních záznamů Ovce i Prasete - kolekce SeznamVeterinarnichZaznamu_Ovce * Prase
/// </summary>
public void UlozVeterina()
{
XmlSerializer serializer = new XmlSerializer(SeznamVeterinarnichZaznamu_Prase.GetType());
using (StreamWriter sw = new StreamWriter(cestaVeterina))
{
serializer.Serialize(sw, SeznamVeterinarnichZaznamu_Prase);
}
using (StreamWriter sw = new StreamWriter(cestaVeterina_Ovce))
{
serializer.Serialize(sw, SeznamVeterinarnichZaznamu_Ovce);
}
}
/// <summary>
/// Načtení všech veterinárních záznamů Ovce i Prasete - kolekce SeznamVeterinarnichZaznamu_Ovce * Prase
/// </summary>
public void NactiVeterina()
{
XmlSerializer serializer = new XmlSerializer(SeznamVeterinarnichZaznamu_Prase.GetType());
if (File.Exists(cestaVeterina))
{
using (StreamReader sr = new StreamReader(cestaVeterina))
{
SeznamVeterinarnichZaznamu_Prase = (ObservableCollection<Veterina>)serializer.Deserialize(sr);
}
}
else
SeznamVeterinarnichZaznamu_Prase = new ObservableCollection<Veterina>();
if (File.Exists(cestaVeterina_Ovce))
{
using (StreamReader sr = new StreamReader(cestaVeterina_Ovce))
{
SeznamVeterinarnichZaznamu_Ovce = (ObservableCollection<Veterina>)serializer.Deserialize(sr);
}
}
else
SeznamVeterinarnichZaznamu_Ovce = new ObservableCollection<Veterina>();
}
#endregion
}
}
| 39.861502 | 225 | 0.480455 | [
"MIT"
] | Pivojak/EvidenceZvirat | Classes/SpravceZvirat.cs | 85,839 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.