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
sequence | repository_name
stringlengths 7
92
| path
stringlengths 3
249
| size
int64 5
1.04M
| lang
stringclasses 2
values |
---|---|---|---|---|---|---|---|---|
using System;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using NeoSharp.BinarySerialization;
using NeoSharp.BinarySerialization.SerializationHooks;
namespace NeoSharp.Types.Converters
{
public class Fixed8TypeConverter : TypeConverter, IBinaryCustomSerializable
{
public static readonly int FixedLength = 8;
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
return destinationType == typeof(Fixed8) || destinationType == typeof(long) || destinationType == typeof(byte[]) || destinationType == typeof(string);
}
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
if (value is Fixed8 val)
{
if (destinationType == typeof(Fixed8)) return value;
if (destinationType == typeof(long)) return val.Value;
if (destinationType == typeof(byte[])) return BitConverter.GetBytes(val.Value);
if (destinationType == typeof(string)) return val.ToString();
}
if (value == null)
{
return null;
}
return base.ConvertTo(context, culture, value, destinationType);
}
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return sourceType == typeof(Fixed8) || sourceType == typeof(long) || sourceType == typeof(byte[]) || sourceType == typeof(string);
}
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
if (value is Fixed8)
{
return value;
}
if (value is byte[] bytes && bytes.Length == FixedLength)
{
return new Fixed8(BitConverter.ToInt64(bytes, 0));
}
if (value is long l)
{
return new Fixed8(l);
}
if (value is string str && Fixed8.TryParse(str, out var res))
{
return res;
}
return base.ConvertFrom(context, culture, value);
}
public object Deserialize(IBinarySerializer binaryDeserializer, BinaryReader reader, Type type, BinarySerializerSettings settings = null)
{
var val = reader.ReadInt64();
return new Fixed8(val);
}
public int Serialize(IBinarySerializer binarySerializer, BinaryWriter writer, object value, BinarySerializerSettings settings = null)
{
if (value is Fixed8 f8)
{
writer.Write(f8.Value);
return FixedLength;
}
throw new ArgumentException(nameof(value));
}
}
} | 35.158537 | 162 | 0.593132 | [
"MIT"
] | BSathvik/neo-sharp | src/NeoSharp.Types/Converters/Fixed8TypeConverter.cs | 2,885 | C# |
// <auto-generated />
namespace MOE.Common.Migrations
{
using System.CodeDom.Compiler;
using System.Data.Entity.Migrations;
using System.Data.Entity.Migrations.Infrastructure;
using System.Resources;
[GeneratedCode("EntityFramework.Migrations", "6.4.4")]
public sealed partial class YellowRedActivationAggregateChange : IMigrationMetadata
{
private readonly ResourceManager Resources = new ResourceManager(typeof(YellowRedActivationAggregateChange));
string IMigrationMetadata.Id
{
get { return "202103042041127_YellowRedActivationAggregateChange"; }
}
string IMigrationMetadata.Source
{
get { return null; }
}
string IMigrationMetadata.Target
{
get { return Resources.GetString("Target"); }
}
}
}
| 29.3 | 117 | 0.646189 | [
"Apache-2.0"
] | avenueconsultants/ATSPM | MOE.Common/Migrations/202103042041127_YellowRedActivationAggregateChange.Designer.cs | 881 | C# |
using AuthBot;
using AzureBot.Domain;
using AzureBot.Forms;
using AzureBot.Helpers;
using AzureBot.Models;
using AzureBot.Services.Runbooks.Forms;
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Builder.FormFlow;
using Microsoft.Bot.Builder.Luis;
using Microsoft.Bot.Builder.Luis.Models;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AzureBot.Dialogs
{
[LuisModel("6ca45971-e419-4e43-8ba4-71fb486d3ffc", "110c81d75bdb4f918a991696cd09f66b")]
[Serializable]
public class AutomationDialog : AzureBotLuisDialog<string>
{
[LuisIntent("None")]
public async Task None(IDialogContext context, LuisResult result)
{
context.Done(result.Query);
}
private static Lazy<string> resourceId = new Lazy<string>(() => ConfigurationManager.AppSettings["ActiveDirectory.ResourceId"]);
[LuisIntent("ListRunbooks")]
public async Task ListRunbooksAsync(IDialogContext context, LuisResult result)
{
var accessToken = await context.GetAccessToken(resourceId.Value);
if (string.IsNullOrEmpty(accessToken))
{
return;
}
var subscriptionId = context.GetSubscriptionId();
var automationAccounts = await new AutomationDomain().ListRunbooksAsync(accessToken, subscriptionId);
if (automationAccounts.Any())
{
var automationAccountsWithRunbooks = automationAccounts.Where(x => x.Runbooks.Any());
if (automationAccountsWithRunbooks.Any())
{
var messageText = "Available runbooks are:";
var singleAutomationAccount = automationAccountsWithRunbooks.Count() == 1;
if (singleAutomationAccount)
{
messageText = $"Listing all runbooks from {automationAccountsWithRunbooks.Single().AutomationAccountName}";
}
var runbooksText = automationAccountsWithRunbooks.Aggregate(
string.Empty,
(current, next) =>
{
var innerRunbooksText = next.Runbooks.Aggregate(
string.Empty,
(currentRunbooks, nextRunbook) =>
{
return currentRunbooks += $"\n\r• {nextRunbook}";
});
return current += singleAutomationAccount ? innerRunbooksText : $"\n\r {next.AutomationAccountName}" + innerRunbooksText;
});
var showDescriptionText = "Type **show runbook <name> description** to get details on any runbook.";
await context.PostAsync($"{messageText}:\r\n {runbooksText} \r\n\r\n {showDescriptionText}");
}
else
{
await context.PostAsync($"The automation accounts found in the current subscription doesn't have runbooks.");
}
}
else
{
await context.PostAsync("No runbooks listed since no automations accounts were found in the current subscription.");
}
context.Done<string>(null);
}
[LuisIntent("ListAutomationAccounts")]
public async Task ListAutomationAccountsAsync(IDialogContext context, LuisResult result)
{
var accessToken = await context.GetAccessToken(resourceId.Value);
if (string.IsNullOrEmpty(accessToken))
{
return;
}
var subscriptionId = context.GetSubscriptionId();
var automationAccounts = await new AutomationDomain().ListAutomationAccountsAsync(accessToken, subscriptionId);
if (automationAccounts.Any())
{
var automationAccountsText = automationAccounts.Aggregate(
string.Empty,
(current, next) =>
{
return current += $"\n\r• {next.AutomationAccountName}";
});
await context.PostAsync($"Available automations accounts are:\r\n {automationAccountsText}");
}
else
{
await context.PostAsync("No automations accounts were found in the current subscription.");
}
context.Done<string>(null);
}
[LuisIntent("RunRunbook")]
public async Task StartRunbookAsync(IDialogContext context, LuisResult result)
{
EntityRecommendation runbookEntity;
var accessToken = await context.GetAccessToken(resourceId.Value);
if (string.IsNullOrEmpty(accessToken))
{
return;
}
var subscriptionId = context.GetSubscriptionId();
var availableAutomationAccounts = await new AutomationDomain().ListRunbooksAsync(accessToken, subscriptionId);
// check if the user specified a runbook name in the command
if (result.TryFindEntity("Runbook", out runbookEntity))
{
// obtain the name specified by the user - text in LUIS result is different
var runbookName = runbookEntity.GetEntityOriginalText(result.Query);
EntityRecommendation automationAccountEntity;
if (result.TryFindEntity("AutomationAccount", out automationAccountEntity))
{
// obtain the name specified by the user - text in LUIS result is different
var automationAccountName = automationAccountEntity.GetEntityOriginalText(result.Query);
var selectedAutomationAccount = availableAutomationAccounts.SingleOrDefault(x => x.AutomationAccountName.Equals(automationAccountName, StringComparison.InvariantCultureIgnoreCase));
if (selectedAutomationAccount == null)
{
await context.PostAsync($"The '{automationAccountName}' automation account was not found in the current subscription");
context.Done<string>(null);
return;
}
var runbook = selectedAutomationAccount.Runbooks.SingleOrDefault(x => x.RunbookName.Equals(runbookName, StringComparison.InvariantCultureIgnoreCase));
// ensure that the runbook exists in the specified automation account
if (runbook == null)
{
await context.PostAsync($"The '{runbookName}' runbook was not found in the '{automationAccountName}' automation account.");
context.Done<string>(null);
return;
}
if (!runbook.RunbookState.Equals("Published", StringComparison.InvariantCultureIgnoreCase))
{
await context.PostAsync($"The '{runbookName}' runbook that you are trying to run is not published (State: {runbook.RunbookState}). Please go the Azure Portal and publish the runbook.");
context.Done<string>(null);
return;
}
runbookEntity.Entity = runbookName;
runbookEntity.Type = "RunbookName";
automationAccountEntity.Entity = selectedAutomationAccount.AutomationAccountName;
automationAccountEntity.Type = "AutomationAccountName";
}
else
{
// ensure that the runbook exists in at least one of the automation accounts
var selectedAutomationAccounts = availableAutomationAccounts.Where(x => x.Runbooks.Any(r => r.RunbookName.Equals(runbookName, StringComparison.InvariantCultureIgnoreCase)));
if (selectedAutomationAccounts == null || !selectedAutomationAccounts.Any())
{
await context.PostAsync($"The '{runbookName}' runbook was not found in any of your automation accounts.");
context.Done<string>(null);
return;
}
var runbooks = selectedAutomationAccounts.SelectMany(x => x.Runbooks.Where(r => r.RunbookName.Equals(runbookName, StringComparison.InvariantCultureIgnoreCase)
&& r.RunbookState.Equals("Published", StringComparison.InvariantCultureIgnoreCase)));
if (runbooks == null || !runbooks.Any())
{
await context.PostAsync($"The '{runbookName}' runbook that you are trying to run is not Published. Please go the Azure Portal and publish the runbook.");
context.Done<string>(null);
return;
}
runbookEntity.Entity = runbookName;
runbookEntity.Type = "RunbookName";
// todo: handle runbooks with same name in different automation accounts
availableAutomationAccounts = selectedAutomationAccounts.ToList();
}
}
if (availableAutomationAccounts.Any())
{
var formState = new RunbookFormState(availableAutomationAccounts);
if (availableAutomationAccounts.Count() == 1)
{
formState.AutomationAccountName = availableAutomationAccounts.Single().AutomationAccountName;
}
var form = new FormDialog<RunbookFormState>(
formState,
AutomationForms.BuildRunbookForm,
FormOptions.PromptInStart,
result.Entities);
context.Call(form, this.StartRunbookParametersAsync);
}
else
{
await context.PostAsync($"No automations accounts were found in the current subscription. Please create an Azure automation account or switch to a subscription which has an automation account in it.");
context.Done<string>(null);
}
}
[LuisIntent("StatusJob")]
public async Task StatusJobAsync(IDialogContext context, LuisResult result)
{
var accessToken = await context.GetAccessToken(resourceId.Value);
if (string.IsNullOrEmpty(accessToken))
{
return;
}
var subscriptionId = context.GetSubscriptionId();
IList<RunbookJob> automationJobs = context.GetAutomationJobs(subscriptionId);
if (automationJobs != null && automationJobs.Any())
{
var messageBuilder = new StringBuilder();
messageBuilder.AppendLine("|Id|Runbook|Start Time|End Time|Status|");
messageBuilder.AppendLine("|---|---|---|---|---|");
foreach (var job in automationJobs)
{
var automationJob = await new AutomationDomain().GetAutomationJobAsync(accessToken, subscriptionId, job.ResourceGroupName, job.AutomationAccountName, job.JobId, configureAwait: false);
var startDateTime = automationJob.StartDateTime?.ToString("g") ?? string.Empty;
var endDateTime = automationJob.EndDateTime?.ToString("g") ?? string.Empty;
var status = automationJob.Status ?? string.Empty;
messageBuilder.AppendLine($"|{job.FriendlyJobId}|{automationJob.RunbookName}|{startDateTime}|{endDateTime}|{status}|");
}
await context.PostAsync(messageBuilder.ToString());
}
else
{
await context.PostAsync("No Runbook Jobs were created in the current session. To create a new Runbook Job type: Start Runbook.");
}
context.Done<string>(null);
}
[LuisIntent("ShowJobOutput")]
public async Task ShowJobOutputAsync(IDialogContext context, LuisResult result)
{
EntityRecommendation jobEntity;
var accessToken = await context.GetAccessToken(resourceId.Value);
if (string.IsNullOrEmpty(accessToken))
{
return;
}
var subscriptionId = context.GetSubscriptionId();
if (result.TryFindEntity("Job", out jobEntity))
{
// obtain the name specified by the user -text in LUIS result is different
var friendlyJobId = jobEntity.GetEntityOriginalText(result.Query);
IList<RunbookJob> automationJobs = context.GetAutomationJobs(subscriptionId);
if (automationJobs != null)
{
var selectedJob = automationJobs.SingleOrDefault(x => !string.IsNullOrWhiteSpace(x.FriendlyJobId)
&& x.FriendlyJobId.Equals(friendlyJobId, StringComparison.InvariantCultureIgnoreCase));
if (selectedJob == null)
{
await context.PostAsync($"The job with id '{friendlyJobId}' was not found.");
context.Done<string>(null);
return;
}
var jobOutput = await new AutomationDomain().GetAutomationJobOutputAsync(accessToken, subscriptionId, selectedJob.ResourceGroupName, selectedJob.AutomationAccountName, selectedJob.JobId);
var outputMessage = string.IsNullOrWhiteSpace(jobOutput) ? $"No output for job '{friendlyJobId}'" : jobOutput;
await context.PostAsync(outputMessage);
}
else
{
await context.PostAsync($"The job with id '{friendlyJobId}' was not found.");
}
}
else
{
await context.PostAsync("No runbook job id was specified. Try 'show <jobId> output'.");
}
context.Done<string>(null);
}
[LuisIntent("ShowRunbookDescription")]
public async Task ShowRunbookDescriptionAsync(IDialogContext context, LuisResult result)
{
EntityRecommendation runbookEntity;
var accessToken = await context.GetAccessToken(resourceId.Value);
if (string.IsNullOrEmpty(accessToken))
{
return;
}
var subscriptionId = context.GetSubscriptionId();
var availableAutomationAccounts = await new AutomationDomain().ListRunbooksAsync(accessToken, subscriptionId);
// check if the user specified a runbook name in the command
if (result.TryFindEntity("Runbook", out runbookEntity))
{
// obtain the name specified by the user - text in LUIS result is different
var runbookName = runbookEntity.GetEntityOriginalText(result.Query);
// ensure that the runbook exists in at least one of the automation accounts
var selectedAutomationAccounts = availableAutomationAccounts.Where(x => x.Runbooks.Any(r => r.RunbookName.Equals(runbookName, StringComparison.InvariantCultureIgnoreCase)));
if (selectedAutomationAccounts == null || !selectedAutomationAccounts.Any())
{
await context.PostAsync($"The '{runbookName}' runbook was not found in any of your automation accounts.");
context.Done<string>(null);
return;
}
if (selectedAutomationAccounts.Count() == 1)
{
var automationAccount = selectedAutomationAccounts.Single();
var runbook = automationAccount.Runbooks.Single(r => r.RunbookName.Equals(runbookName, StringComparison.InvariantCultureIgnoreCase));
var description = await new AutomationDomain().GetAutomationRunbookDescriptionAsync(accessToken, subscriptionId, automationAccount.ResourceGroup, automationAccount.AutomationAccountName, runbook.RunbookName) ?? "No description";
await context.PostAsync(description);
context.Done<string>(null);
}
else
{
var message = $"I found the runbook '{runbookName}' in multiple automation accounts. Showing the description of all of them:";
foreach (var automationAccount in selectedAutomationAccounts)
{
message += $"\n\r {automationAccount.AutomationAccountName}";
foreach (var runbook in automationAccount.Runbooks)
{
if (runbook.RunbookName.Equals(runbookName, StringComparison.InvariantCultureIgnoreCase))
{
var description = await new AutomationDomain().GetAutomationRunbookDescriptionAsync(accessToken, subscriptionId, automationAccount.ResourceGroup, automationAccount.AutomationAccountName, runbook.RunbookName) ?? "No description";
message += $"\n\r• {description}";
}
}
}
await context.PostAsync(message);
context.Done<string>(null);
}
}
else
{
await context.PostAsync($"No runbook was specified. Please try again specifying a runbook name.");
context.Done<string>(null);
}
}
private async Task StartRunbookParametersAsync(IDialogContext context, IAwaitable<RunbookFormState> result)
{
try
{
var runbookFormState = await result;
context.StoreRunbookFormState(runbookFormState);
await this.RunbookParametersFormComplete(context, null);
}
catch (FormCanceledException<RunbookFormState> e)
{
string reply;
if (e.InnerException == null)
{
reply = "You have canceled the operation. What would you like to do next?";
}
else
{
reply = $"Oops! Something went wrong :(. Technical Details: {e.InnerException.Message}";
}
await context.PostAsync(reply);
context.Done<string>(null);
}
}
private async Task RunbookParametersFormComplete(IDialogContext context, RunbookParameterFormState runbookParameterFormState)
{
var runbookFormState = context.GetRunbookFormState();
if (runbookParameterFormState != null)
{
runbookFormState.RunbookParameters.Add(runbookParameterFormState);
context.StoreRunbookFormState(runbookFormState);
}
var nextRunbookParameter = runbookFormState.SelectedRunbook.RunbookParameters.OrderBy(param => param.Position).FirstOrDefault(
availableParam => !runbookFormState.RunbookParameters.Any(stateParam => availableParam.ParameterName == stateParam.ParameterName));
if (nextRunbookParameter == null)
{
context.CleanupRunbookFormState();
await this.RunbookFormComplete(context, runbookFormState);
return;
}
var formState = new RunbookParameterFormState(nextRunbookParameter.IsMandatory, nextRunbookParameter.Position == 0, runbookFormState.SelectedRunbook.RunbookName)
{
ParameterName = nextRunbookParameter.ParameterName
};
var form = new FormDialog<RunbookParameterFormState>(
formState,
AutomationForms.BuildRunbookParametersForm,
FormOptions.PromptInStart);
context.Call(form, this.RunbookParameterFormComplete);
}
private async Task RunbookParameterFormComplete(IDialogContext context, IAwaitable<RunbookParameterFormState> result)
{
try
{
var runbookParameterFormState = await result;
await this.RunbookParametersFormComplete(context, runbookParameterFormState);
}
catch (FormCanceledException<RunbookParameterFormState> e)
{
context.CleanupRunbookFormState();
string reply;
if (e.InnerException == null)
{
reply = "You have canceled the operation. What would you like to do next?";
}
else
{
reply = $"Oops! Something went wrong :(. Technical Details: {e.InnerException.Message}";
}
await context.PostAsync(reply);
context.Done<string>(null);
}
}
private async Task RunbookFormComplete(IDialogContext context, RunbookFormState runbookFormState)
{
try
{
var accessToken = await context.GetAccessToken(resourceId.Value);
if (string.IsNullOrEmpty(accessToken))
{
return;
}
var runbookJob = await new AutomationDomain().StartRunbookAsync(
accessToken,
runbookFormState.SelectedAutomationAccount.SubscriptionId,
runbookFormState.SelectedAutomationAccount.ResourceGroup,
runbookFormState.SelectedAutomationAccount.AutomationAccountName,
runbookFormState.RunbookName,
runbookFormState.RunbookParameters.Where(param => !string.IsNullOrWhiteSpace(param.ParameterValue))
.ToDictionary(param => param.ParameterName, param => param.ParameterValue));
IList<RunbookJob> automationJobs = context.GetAutomationJobs(runbookFormState.SelectedAutomationAccount.SubscriptionId);
if (automationJobs == null)
{
runbookJob.FriendlyJobId = AutomationJobsHelper.NextFriendlyJobId(automationJobs);
automationJobs = new List<RunbookJob> { runbookJob };
}
else
{
runbookJob.FriendlyJobId = AutomationJobsHelper.NextFriendlyJobId(automationJobs);
automationJobs.Add(runbookJob);
}
context.StoreAutomationJobs(runbookFormState.SelectedAutomationAccount.SubscriptionId, automationJobs);
await context.PostAsync($"Created Job '{runbookJob.JobId}' for the '{runbookFormState.RunbookName}' runbook in '{runbookFormState.AutomationAccountName}' automation account. You'll receive a message when it is completed.");
var notCompletedStatusList = new List<string> { "Stopped", "Suspended", "Failed" };
var completedStatusList = new List<string> { "Completed" };
var notifyStatusList = new List<string> { "Running" };
notifyStatusList.AddRange(completedStatusList);
notifyStatusList.AddRange(notCompletedStatusList);
accessToken = await context.GetAccessToken(resourceId.Value);
if (string.IsNullOrEmpty(accessToken))
{
return;
}
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
CheckLongRunningOperationStatus(
context,
runbookJob,
accessToken,
new AutomationDomain().GetAutomationJobAsync,
rj => rj.EndDateTime.HasValue,
(previous, last, job) =>
{
if (!string.Equals(previous?.Status, last?.Status) && notifyStatusList.Contains(last.Status))
{
if (notCompletedStatusList.Contains(last.Status))
{
return $"The runbook '{job.RunbookName}' (job '{job.JobId}') did not complete with status '{last.Status}'. Please go to the Azure Portal for more detailed information on why.";
}
else if (completedStatusList.Contains(last.Status))
{
return $"Runbook '{job.RunbookName}' is currently in '{last.Status}' status. Type **show {job.FriendlyJobId} output** to see the output.";
}
else
{
return $"Runbook '{job.RunbookName}' job '{job.JobId}' is currently in '{last.Status}' status.";
}
}
return null;
});
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
}
catch (Exception e)
{
await context.PostAsync($"Oops! Something went wrong :(. Technical Details: {e.InnerException.Message}");
}
context.Done<string>(null);
}
private static async Task CheckLongRunningOperationStatus<T>(IDialogContext context, RunbookJob automationJob, string accessToken,
Func<string, string, string, string, string, bool, Task<T>> getOperationStatusAsync, Func<T, bool> completionCondition,
Func<T, T, RunbookJob, string> getOperationStatusMessage, int delayBetweenPoolingInSeconds = 2)
{
var lastOperationStatus = default(T);
do
{
var subscriptionId = context.GetSubscriptionId();
var newOperationStatus = await getOperationStatusAsync(accessToken, subscriptionId, automationJob.ResourceGroupName, automationJob.AutomationAccountName, automationJob.JobId, true).ConfigureAwait(false);
var message = getOperationStatusMessage(lastOperationStatus, newOperationStatus, automationJob);
await context.NotifyUser(message);
await Task.Delay(TimeSpan.FromSeconds(delayBetweenPoolingInSeconds)).ConfigureAwait(false);
lastOperationStatus = newOperationStatus;
}
while (!completionCondition(lastOperationStatus));
}
}
}
| 46.530928 | 260 | 0.576899 | [
"MIT"
] | Bhaskers-Blu-Org2/AzureBot | AzureBot.Services.Runbooks/Dialogs/AutomationDialog.cs | 27,089 | C# |
//========= Copyright 2016, HTC Corporation. All rights reserved. ===========
using HTC.UnityPlugin.PoseTracker;
using System;
using UnityEngine;
using UnityEngine.Events;
namespace HTC.UnityPlugin.Vive
{
[AddComponentMenu("HTC/Vive/Vive Pose Tracker")]
// Simple component to track Vive devices.
public class VivePoseTracker : BasePoseTracker, INewPoseListener
{
[Serializable]
public class IsValidChangedEvent : UnityEvent<bool> { }
private bool isValid;
public Transform origin;
public DeviceRole role = DeviceRole.Hmd;
public IsValidChangedEvent onIsValidChanged;
protected virtual void Start()
{
isValid = VivePose.IsValid(role);
onIsValidChanged.Invoke(isValid);
}
protected virtual void OnEnable()
{
VivePose.AddNewPosesListener(this);
}
protected virtual void OnDisable()
{
VivePose.RemoveNewPosesListener(this);
}
public virtual void BeforeNewPoses() { }
public virtual void OnNewPoses()
{
TrackPose(VivePose.GetPose(role), origin);
var isValidCurrent = VivePose.IsValid(role);
if (isValid != isValidCurrent)
{
isValid = isValidCurrent;
onIsValidChanged.Invoke(isValid);
}
}
public virtual void AfterNewPoses() { }
}
} | 26.527273 | 78 | 0.603153 | [
"MIT"
] | aidankmcl/A-tech-of-the-Blocks | Assets/HTC.UnityPlugin/ViveInputUtility/Scripts/VivePose/VivePoseTracker.cs | 1,461 | C# |
using TestDummies.Console.Themes;
namespace Serilog.Settings.Combined.Tests.Support
{
public class MyCustomConsoleTheme : ConsoleTheme
{
}
}
| 17.222222 | 52 | 0.748387 | [
"Apache-2.0"
] | serilog/serilog-settings-combined | test/Serilog.Settings.Combined.Tests/Support/MyCustomConsoleTheme.cs | 157 | C# |
// Copyright (c) Microsoft Open Technologies, Inc. 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;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
namespace Microsoft.CodeAnalysis.FxCopAnalyzers.Performance
{
/// <summary>
/// CA1821: Remove empty finalizers
/// </summary>
[ExportCodeFixProvider(CA1821DiagnosticAnalyzerRule.RuleId, LanguageNames.CSharp, LanguageNames.VisualBasic), Shared]
public sealed class CA1821CodeFixProvider : CodeFixProviderBase
{
public sealed override ImmutableArray<string> GetFixableDiagnosticIds()
{
return ImmutableArray.Create(CA1821DiagnosticAnalyzerRule.RuleId);
}
protected sealed override string GetCodeFixDescription(Diagnostic diagnostic)
{
return FxCopFixersResources.RemoveEmptyFinalizers;
}
internal override Task<Document> GetUpdatedDocumentAsync(Document document, SemanticModel model, SyntaxNode root, SyntaxNode nodeToFix, Diagnostic diagnostic, CancellationToken cancellationToken)
{
return Task.FromResult(document.WithSyntaxRoot(root.RemoveNode(nodeToFix, SyntaxRemoveOptions.KeepNoTrivia)));
}
}
} | 43.1875 | 203 | 0.753256 | [
"Apache-2.0"
] | enginekit/copy_of_roslyn | Src/Diagnostics/FxCop/Core/Performance/CodeFixes/CA1821CodeFixProvider.cs | 1,384 | C# |
#pragma warning disable 1591
// ------------------------------------------------------------------------------
// <autogenerated>
// This code was generated by a tool.
// Mono Runtime Version: 4.0.30319.17020
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </autogenerated>
// ------------------------------------------------------------------------------
[assembly: Android.Runtime.ResourceDesignerAttribute("MessageBoxAndroid.Resource", IsApplication=true)]
namespace MessageBoxAndroid
{
[System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Android.Build.Tasks", "1.0.0.0")]
public partial class Resource
{
static Resource()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
public static void UpdateIdValues()
{
}
public partial class Attribute
{
static Attribute()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private Attribute()
{
}
}
public partial class Drawable
{
// aapt resource value: 0x7f020000
public const int Icon = 2130837504;
static Drawable()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private Drawable()
{
}
}
public partial class Id
{
// aapt resource value: 0x7f050006
public const int btnCustomEvent = 2131034118;
// aapt resource value: 0x7f050002
public const int btnDeRegister = 2131034114;
// aapt resource value: 0x7f050000
public const int btnRegister = 2131034112;
// aapt resource value: 0x7f050005
public const int btnSendMessage = 2131034117;
// aapt resource value: 0x7f050001
public const int btnShowPoster = 2131034113;
// aapt resource value: 0x7f050004
public const int edtMessage = 2131034116;
// aapt resource value: 0x7f050003
public const int txtOutput = 2131034115;
static Id()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private Id()
{
}
}
public partial class Layout
{
// aapt resource value: 0x7f030000
public const int Main = 2130903040;
// aapt resource value: 0x7f030001
public const int Second = 2130903041;
static Layout()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private Layout()
{
}
}
public partial class String
{
// aapt resource value: 0x7f040001
public const int app_name = 2130968577;
// aapt resource value: 0x7f040000
public const int hello = 2130968576;
static String()
{
global::Android.Runtime.ResourceIdManager.UpdateIdValues();
}
private String()
{
}
}
}
}
#pragma warning restore 1591
| 20.746269 | 103 | 0.626259 | [
"MIT"
] | degendra/MessageBus | samples/Android/Resources/Resource.designer.cs | 2,780 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Principle4.DryLogic.Validation
{
public class PropertyRule : Rule
{
public PropertyRule(PropertyDefinition propertyDefinition)
{
Property = propertyDefinition;
}
public Boolean ForceEmitClientSide { get; set; }
public PropertyDefinition Property { get; private set; }
}
}
| 19.142857 | 62 | 0.738806 | [
"Apache-2.0"
] | principle4/DryLogic | Principle4.DryLogic/Validation/PropertyRule.cs | 404 | C# |
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using vega.Persistence;
namespace Vega.Migrations
{
[DbContext(typeof(VegaDbContext))]
[Migration("20170815235349_AddVehicle")]
partial class AddVehicle
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
modelBuilder
.HasAnnotation("ProductVersion", "1.1.2")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("vega.Models.Feature", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(255);
b.HasKey("Id");
b.ToTable("Feature");
});
modelBuilder.Entity("vega.Models.Make", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(255);
b.HasKey("Id");
b.ToTable("Makes");
});
modelBuilder.Entity("vega.Models.Model", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int>("MakeId");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(255);
b.HasKey("Id");
b.HasIndex("MakeId");
b.ToTable("Models");
});
modelBuilder.Entity("vega.Models.Vehicle", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ContactEmail")
.HasMaxLength(255);
b.Property<string>("ContactName")
.IsRequired()
.HasMaxLength(255);
b.Property<string>("ContactPhone")
.IsRequired()
.HasMaxLength(255);
b.Property<bool>("IsRegister");
b.Property<DateTime>("LastUpdate");
b.Property<int>("ModelId");
b.HasKey("Id");
b.HasIndex("ModelId");
b.ToTable("Vehicles");
});
modelBuilder.Entity("vega.Models.VehicleFeature", b =>
{
b.Property<int>("VehicleId");
b.Property<int>("FeatureId");
b.HasKey("VehicleId", "FeatureId");
b.HasIndex("FeatureId");
b.ToTable("VehicleFeatures");
});
modelBuilder.Entity("vega.Models.Model", b =>
{
b.HasOne("vega.Models.Make", "Make")
.WithMany("Models")
.HasForeignKey("MakeId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("vega.Models.Vehicle", b =>
{
b.HasOne("vega.Models.Model", "Model")
.WithMany()
.HasForeignKey("ModelId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("vega.Models.VehicleFeature", b =>
{
b.HasOne("vega.Models.Feature", "Feature")
.WithMany()
.HasForeignKey("FeatureId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("vega.Models.Vehicle", "Vehicle")
.WithMany("Features")
.HasForeignKey("VehicleId")
.OnDelete(DeleteBehavior.Cascade);
});
}
}
}
| 31.007194 | 117 | 0.435963 | [
"MIT"
] | FernandoPucci/AspNetCore | vega/Migrations/20170815235349_AddVehicle.Designer.cs | 4,312 | C# |
using System;
using System.Collections.Generic;
using Server;
namespace Server.Mobiles
{
public class Shipwright : BaseVendor
{
private List<SBInfo> m_SBInfos = new List<SBInfo>();
protected override List<SBInfo> SBInfos{ get { return m_SBInfos; } }
[Constructable]
public Shipwright() : base( "l'Armateur", "l'Armatrice" )
{
SetSkill( SkillName.Carpentry, 60.0, 83.0 );
SetSkill( SkillName.Macing, 36.0, 68.0 );
}
public override void InitSBInfo()
{
m_SBInfos.Add( new SBShipwright() );
}
public override void InitOutfit()
{
base.InitOutfit();
AddItem( new Server.Items.SmithHammer() );
}
public Shipwright( Serial serial ) : base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 0 ); // version
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadInt();
}
}
} | 20.44898 | 71 | 0.652695 | [
"BSD-2-Clause"
] | greeduomacro/vivre-uo | Scripts/Mobiles/Vendors/NPC/Shipwright.cs | 1,002 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
namespace WpfApp3
{
class Login
{
//decalre properties
public string Username { get; set; }
public string Userpassword { get; set; }
//intialise
public Login(string user, string pass)
{
this.Username = user;
this.Userpassword = pass;
}
//validate string
private bool StringValidator(string input)
{
string pattern = "[^a-zA-Z]";
if (Regex.IsMatch(input, pattern))
{
return true;
}
else
{
return false;
}
}
//validate integer
private bool IntegerValidator(string input)
{
string pattern = "[^0-9]";
if (Regex.IsMatch(input, pattern))
{
return true;
}
else
{
return false;
}
}
//clear user inputs
private void ClearTexts(string user, string pass)
{
user = String.Empty;
pass = String.Empty;
}
//method to check if eligible to be logged in
internal bool IsLoggedIn(string user, string pass)
{
//check user name empty
if (string.IsNullOrEmpty(user))
{
return false;
}
//check user name is valid type
else if (StringValidator(user) == true)
{
MessageBox.Show("Enter only text here");
ClearTexts(user, pass);
return false;
}
//check user name is correct
else
{
if (Username != user)
{
ClearTexts(user, pass);
return false;
}
//check password is empty
else
{
if (string.IsNullOrEmpty(pass))
{
return false;
}
//check password is valid
else if (IntegerValidator(pass) == true)
{
MessageBox.Show("Enter only integer here");
return false;
}
//check password is correct
else if (Userpassword != pass)
{
return false;
}
else
{
return true;
}
}
}
}
}
}
| 27.066038 | 67 | 0.41199 | [
"MIT"
] | SnippingAddict/VinarijaTimok | WpfApp3/Login.cs | 2,871 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the autoscaling-plans-2018-01-06.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.AutoScalingPlans.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.AutoScalingPlans.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for DeleteScalingPlan operation
/// </summary>
public class DeleteScalingPlanResponseUnmarshaller : JsonResponseUnmarshaller
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
{
DeleteScalingPlanResponse response = new DeleteScalingPlanResponse();
return response;
}
/// <summary>
/// Unmarshaller error response to exception.
/// </summary>
/// <param name="context"></param>
/// <param name="innerException"></param>
/// <param name="statusCode"></param>
/// <returns></returns>
public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
{
var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context);
errorResponse.InnerException = innerException;
errorResponse.StatusCode = statusCode;
var responseBodyBytes = context.GetResponseBodyBytes();
using (var streamCopy = new MemoryStream(responseBodyBytes))
using (var contextCopy = new JsonUnmarshallerContext(streamCopy, false, null))
{
if (errorResponse.Code != null && errorResponse.Code.Equals("ConcurrentUpdateException"))
{
return ConcurrentUpdateExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("InternalServiceException"))
{
return InternalServiceExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ObjectNotFoundException"))
{
return ObjectNotFoundExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ValidationException"))
{
return ValidationExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
}
return new AmazonAutoScalingPlansException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode);
}
private static DeleteScalingPlanResponseUnmarshaller _instance = new DeleteScalingPlanResponseUnmarshaller();
internal static DeleteScalingPlanResponseUnmarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static DeleteScalingPlanResponseUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 39.585586 | 199 | 0.662039 | [
"Apache-2.0"
] | DetlefGolze/aws-sdk-net | sdk/src/Services/AutoScalingPlans/Generated/Model/Internal/MarshallTransformations/DeleteScalingPlanResponseUnmarshaller.cs | 4,394 | C# |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
namespace Microsoft.WindowsAzure.Management.Automation.Models
{
/// <summary>
/// The parameters supplied to the update runbook properties.
/// </summary>
public partial class RunbookUpdateProperties
{
private string _description;
/// <summary>
/// Optional. Gets or sets the description of the runbook.
/// </summary>
public string Description
{
get { return this._description; }
set { this._description = value; }
}
private bool _logProgress;
/// <summary>
/// Optional. Gets or sets progress log option.
/// </summary>
public bool LogProgress
{
get { return this._logProgress; }
set { this._logProgress = value; }
}
private bool _logVerbose;
/// <summary>
/// Optional. Gets or sets verbose log option.
/// </summary>
public bool LogVerbose
{
get { return this._logVerbose; }
set { this._logVerbose = value; }
}
private string _serviceManagementTags;
/// <summary>
/// Optional. Gets or sets the service management tags of the runbook.
/// </summary>
public string ServiceManagementTags
{
get { return this._serviceManagementTags; }
set { this._serviceManagementTags = value; }
}
/// <summary>
/// Initializes a new instance of the RunbookUpdateProperties class.
/// </summary>
public RunbookUpdateProperties()
{
}
}
}
| 29.857143 | 78 | 0.598884 | [
"Apache-2.0"
] | CerebralMischief/azure-sdk-for-net | src/ServiceManagement/Automation/AutomationManagement/Generated/Models/RunbookUpdateProperties.cs | 2,508 | C# |
namespace Avalonia.Animation.Easings
{
/// <summary>
/// Eases in a <see cref="double"/> value
/// using a quadratic function.
/// </summary>
public class QuadraticEaseIn : Easing
{
/// <inheritdoc/>
public override double Ease(double progress)
{
return progress * progress;
}
}
}
| 22.125 | 52 | 0.559322 | [
"MIT"
] | 0x0ade/Avalonia | src/Avalonia.Base/Animation/Easings/QuadraticEaseIn.cs | 354 | C# |
/*
* Copyright 2018 Sage Intacct, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "LICENSE" file accompanying this file. This file is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System;
using System.Collections.Generic;
using Intacct.SDK.Xml;
namespace Intacct.SDK.Functions.AccountsReceivable
{
public abstract class AbstractInvoiceLine : IXmlObject
{
public string AccountLabel;
public string GlAccountNumber;
public string OffsetGlAccountNumber;
public decimal? TransactionAmount;
public string AllocationId;
public string Memo;
public int? Key;
public decimal? TotalPaid;
public decimal? TotalDue;
public string RevRecTemplateId;
public string DeferredRevGlAccountNo;
public DateTime? RevRecStartDate;
public DateTime? RevRecEndDate;
public string DepartmentId;
public string LocationId;
public string ProjectId;
public string CustomerId;
public string VendorId;
public string EmployeeId;
public string ItemId;
public string ClassId;
public string ContractId;
public string WarehouseId;
public Dictionary<string, dynamic> CustomFields = new Dictionary<string, dynamic>();
protected AbstractInvoiceLine()
{
}
public abstract void WriteXml(ref IaXmlWriter xml);
}
} | 23 | 92 | 0.672283 | [
"Apache-2.0"
] | michaelpaulus/intacct-sdk-net | Intacct.SDK/Functions/AccountsReceivable/AbstractInvoiceLine.cs | 1,842 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace L01ReverseString
{
class Program
{
static void Main(string[] args)
{
string input = Console.ReadLine();
char[] stringToChar = input.ToCharArray();
}
}
}
| 18.944444 | 54 | 0.627566 | [
"MIT"
] | DenicaAtanasova/SoftUni | I_Tech_Module/01. Programming Fundamentals/L11_Strings_And_Text/L01ReverseString/Program.cs | 343 | C# |
using System.Threading.Tasks;
using AGS.API;
using AGS.Engine;
namespace DemoGame
{
public class FeaturesViewportsPanel : IFeaturesPanel
{
private IGame _game;
private IObject _parent;
private bool _isShowing;
private IViewport _viewport1, _viewport2;
public FeaturesViewportsPanel(IGame game, IObject parent)
{
_game = game;
_parent = parent;
}
public Task Close()
{
_isShowing = false;
_game.State.SecondaryViewports.Clear();
return Task.CompletedTask;
}
public async void Show()
{
_isShowing = true;
AGSDisplayListSettings settings1 = new AGSDisplayListSettings
{
DisplayGUIs = false
};
_viewport1 = new AGSViewport(settings1, null);
_viewport1.RoomProvider = new AGSSingleRoomProvider(await Rooms.DarsStreet);
_viewport1.ProjectionBox = new RectangleF(0.125f, 0.07f, 0.25f, 0.25f);
_viewport1.Z = -1f;
_viewport1.Parent = _parent;
_game.State.SecondaryViewports.Add(_viewport1);
AGSDisplayListSettings settings2 = new AGSDisplayListSettings
{
DisplayGUIs = false
};
_viewport2 = new AGSViewport(settings2, null);
_viewport2.RoomProvider = new AGSSingleRoomProvider(await Rooms.BrokenCurbStreet);
_viewport2.ProjectionBox = new RectangleF(0.125f, 0.37f, 0.25f, 0.25f);
_viewport2.Pivot = (0.5f, 0.5f);
_viewport2.X = 180f;
_viewport2.Y = 100f;
_viewport2.Z = -2f;
_viewport2.Parent = _parent;
_game.State.SecondaryViewports.Add(_viewport2);
animate();
}
private async void animate()
{
await Task.Delay(2000);
if (!_isShowing) return;
var task1 = _viewport1.TweenProjectY(0.37f, 1f, Ease.QuadIn).Task;
var task2 = _viewport2.TweenProjectY(0.07f, 1f, Ease.QuadIn).Task;
await Task.WhenAll(task1, task2);
await Task.Delay(1000);
if (!_isShowing) return;
task1 = _viewport1.TweenProjectWidth(0.1f, 1f, Ease.BounceIn).Task;
task2 = _viewport2.TweenProjectWidth(0.1f, 1f, Ease.BounceIn).Task;
await Task.WhenAll(task1, task2);
await Task.Delay(1000);
if (!_isShowing) return;
task1 = _viewport1.TweenProjectY(0.07f, 1f, Ease.SineInOut).Task;
task2 = _viewport2.TweenProjectY(0.37f, 1f, Ease.SineInOut).Task;
var task3 = _viewport1.TweenProjectWidth(0.25f, 1.5f, Ease.SineInOut).Task;
var task4 = _viewport2.TweenProjectWidth(0.25f, 1.5f, Ease.SineInOut).Task;
await Task.WhenAll(task1, task2, task3, task4);
await Task.Delay(1000);
if (!_isShowing) return;
task1 = _viewport1.TweenScaleX(2f, 1f, Ease.CircIn).Task;
task2 = _viewport1.TweenScaleY(2f, 1f, Ease.CircIn).Task;
task3 = _viewport2.TweenAngle(45f, 1f, Ease.ExpoOut).Task;
await Task.WhenAll(task1, task2, task3);
await Task.Delay(1000);
if (!_isShowing) return;
task1 = _viewport1.TweenScaleX(1f, 1f, Ease.CircOut).Task;
task2 = _viewport1.TweenScaleY(1f, 1f, Ease.CircOut).Task;
task3 = _viewport2.TweenAngle(0f, 1f, Ease.ExpoIn).Task;
await Task.WhenAll(task1, task2, task3);
await Task.Delay(1000);
var restrictionList = _viewport2.DisplayListSettings.RestrictionList;
if (restrictionList.RestrictionList.Count == 0)
{
restrictionList.RestrictionType = RestrictionListType.WhiteList;
restrictionList.RestrictionList.Add("Beman");
}
else restrictionList.RestrictionList.Clear();
animate();
}
}
}
| 37.425926 | 94 | 0.589065 | [
"Artistic-2.0"
] | tzachshabtay/MonoAGS | Source/Demo/DemoQuest/GUI/FeaturesWindow/FeaturesViewportsPanel.cs | 4,044 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using NuKeeper.Abstractions;
using NuKeeper.Abstractions.CollaborationPlatform;
using NuKeeper.Abstractions.Configuration;
using NuKeeper.Abstractions.Formats;
using NuKeeper.Abstractions.Logging;
using NuKeeper.AzureDevOps;
using NuKeeper.BitBucket;
using NuKeeper.BitBucketLocal;
using NuKeeper.Engine;
using NuKeeper.Gitea;
using NuKeeper.GitHub;
using NuKeeper.Gitlab;
namespace NuKeeper.Collaboration
{
public class CollaborationFactory : ICollaborationFactory
{
private readonly IEnumerable<ISettingsReader> _settingReaders;
private readonly INuKeeperLogger _nuKeeperLogger;
private Platform? _platform;
public IForkFinder ForkFinder { get; private set; }
public ICommitWorder CommitWorder { get; private set; }
public IRepositoryDiscovery RepositoryDiscovery { get; private set; }
public ICollaborationPlatform CollaborationPlatform { get; private set; }
public CollaborationPlatformSettings Settings { get; }
public CollaborationFactory(IEnumerable<ISettingsReader> settingReaders,
INuKeeperLogger nuKeeperLogger)
{
_settingReaders = settingReaders;
_nuKeeperLogger = nuKeeperLogger;
Settings = new CollaborationPlatformSettings();
}
public async Task<ValidationResult> Initialise(Uri apiEndpoint, string token,
ForkMode? forkModeFromSettings, Platform? platformFromSettings)
{
var platformSettingsReader = await FindPlatformSettingsReader(platformFromSettings, apiEndpoint);
if (platformSettingsReader != null)
{
_platform = platformSettingsReader.Platform;
}
else
{
return ValidationResult.Failure($"Unable to find collaboration platform for uri {apiEndpoint}");
}
Settings.BaseApiUrl = UriFormats.EnsureTrailingSlash(apiEndpoint);
Settings.Token = token;
Settings.ForkMode = forkModeFromSettings;
platformSettingsReader.UpdateCollaborationPlatformSettings(Settings);
var result = ValidateSettings();
if (!result.IsSuccess)
{
return result;
}
CreateForPlatform();
return ValidationResult.Success;
}
private async Task<ISettingsReader> FindPlatformSettingsReader(
Platform? platformFromSettings, Uri apiEndpoint)
{
if (platformFromSettings.HasValue)
{
var reader = _settingReaders
.FirstOrDefault(s => s.Platform == platformFromSettings.Value);
if (reader != null)
{
_nuKeeperLogger.Normal($"Collaboration platform specified as '{reader.Platform}'");
}
return reader;
}
else
{
var reader = await _settingReaders
.FirstOrDefaultAsync(s => s.CanRead(apiEndpoint));
if (reader != null)
{
_nuKeeperLogger.Normal($"Matched uri '{apiEndpoint}' to collaboration platform '{reader.Platform}'");
}
return reader;
}
}
private ValidationResult ValidateSettings()
{
if (!Settings.BaseApiUrl.IsWellFormedOriginalString()
|| (Settings.BaseApiUrl.Scheme != "http" && Settings.BaseApiUrl.Scheme != "https"))
{
return ValidationResult.Failure(
$"Api is not of correct format {Settings.BaseApiUrl}");
}
if (!Settings.ForkMode.HasValue)
{
return ValidationResult.Failure("Fork Mode was not set");
}
if (string.IsNullOrWhiteSpace(Settings.Token))
{
return ValidationResult.Failure("Token was not set");
}
if (!_platform.HasValue)
{
return ValidationResult.Failure("Platform was not set");
}
return ValidationResult.Success;
}
private void CreateForPlatform()
{
var forkMode = Settings.ForkMode.Value;
switch (_platform.Value)
{
case Platform.AzureDevOps:
CollaborationPlatform = new AzureDevOpsPlatform(_nuKeeperLogger);
RepositoryDiscovery = new AzureDevOpsRepositoryDiscovery(_nuKeeperLogger, Settings.Token);
ForkFinder = new AzureDevOpsForkFinder(CollaborationPlatform, _nuKeeperLogger, forkMode);
// We go for the specific platform version of ICommitWorder
// here since Azure DevOps has different commit message limits compared to other platforms.
CommitWorder = new AzureDevOpsCommitWorder();
break;
case Platform.GitHub:
CollaborationPlatform = new OctokitClient(_nuKeeperLogger);
RepositoryDiscovery = new GitHubRepositoryDiscovery(_nuKeeperLogger, CollaborationPlatform);
ForkFinder = new GitHubForkFinder(CollaborationPlatform, _nuKeeperLogger, forkMode);
CommitWorder = new DefaultCommitWorder();
break;
case Platform.Bitbucket:
CollaborationPlatform = new BitbucketPlatform(_nuKeeperLogger);
RepositoryDiscovery = new BitbucketRepositoryDiscovery(_nuKeeperLogger);
ForkFinder = new BitbucketForkFinder(CollaborationPlatform, _nuKeeperLogger, forkMode);
CommitWorder = new BitbucketCommitWorder();
break;
case Platform.BitbucketLocal:
CollaborationPlatform = new BitBucketLocalPlatform(_nuKeeperLogger);
RepositoryDiscovery = new BitbucketLocalRepositoryDiscovery(_nuKeeperLogger, CollaborationPlatform, Settings);
ForkFinder = new BitbucketForkFinder(CollaborationPlatform, _nuKeeperLogger, forkMode);
CommitWorder = new DefaultCommitWorder();
break;
case Platform.GitLab:
CollaborationPlatform = new GitlabPlatform(_nuKeeperLogger);
RepositoryDiscovery = new GitlabRepositoryDiscovery(_nuKeeperLogger, CollaborationPlatform);
ForkFinder = new GitlabForkFinder(CollaborationPlatform, _nuKeeperLogger, forkMode);
CommitWorder = new DefaultCommitWorder();
break;
case Platform.Gitea:
CollaborationPlatform = new GiteaPlatform(_nuKeeperLogger);
RepositoryDiscovery = new GiteaRepositoryDiscovery(_nuKeeperLogger, CollaborationPlatform);
ForkFinder = new GiteaForkFinder(CollaborationPlatform, _nuKeeperLogger, forkMode);
CommitWorder = new DefaultCommitWorder();
break;
default:
throw new NuKeeperException($"Unknown platform: {_platform}");
}
var auth = new AuthSettings(Settings.BaseApiUrl, Settings.Token, Settings.Username);
CollaborationPlatform.Initialise(auth);
if (ForkFinder == null ||
RepositoryDiscovery == null ||
CollaborationPlatform == null)
{
throw new NuKeeperException($"Platform {_platform} could not be initialised");
}
}
}
}
| 39.75 | 130 | 0.608394 | [
"Apache-2.0"
] | Bouke/NuKeeper | NuKeeper/Collaboration/CollaborationFactory.cs | 7,791 | C# |
using System;
namespace CQRS.Commanding.Testing
{
public interface IReplayEvents
{
IReplayEvents Append<TEvent>(Action<TEvent> evt) where TEvent: class, IEvent, new();
}
} | 22.333333 | 93 | 0.666667 | [
"MIT"
] | HAXEN/CQRS | src/CQRS.Commanding.Testing/IReplayEvents.cs | 203 | C# |
// Copyright (c) Stride contributors (https://stride3d.net) and Silicon Studio Corp. (https://www.siliconstudio.co.jp)
// Distributed under the MIT license. See the LICENSE.md file in the project root for more information.
using System;
namespace Stride.Audio
{
/// <summary>
/// Interface for 3D localizable sound.
/// The interface currently supports only mono and stereo sounds (ref <see cref="Pan"/>).
/// The user can localize its sound with <see cref="Apply3D"/> by creating one <see cref="AudioEmitter"/>
/// and one <see cref="AudioListener"/> respectly corresponding to the source of the sound and the listener.
/// The <see cref="Pan"/> function enable the user to change the distribution of sound between the left and right speakers.
/// </summary>
/// <remarks>Functions <see cref="Pan"/> and <see cref="Apply3D"/> cannot be used together.
/// A call to <see cref="Apply3D"/> will reset <see cref="Pan"/> to its default value and inverse.</remarks>
/// <seealso cref="Sound"/>
/// <seealso cref="SoundInstance"/>
public interface IPositionableSound : IPlayableSound
{
/// <summary>
/// Set the sound balance between left and right speaker.
/// </summary>
/// <remarks>Panning is ranging from -1.0f (full left) to 1.0f (full right). 0.0f is centered. Values beyond this range are clamped.
/// Panning modifies the total energy of the signal (Pan == -1 => Energy = 1 + 0, Pan == 0 => Energy = 1 + 1, Pan == 0.5 => Energy = 1 + 0.5, ...)
/// <para>A call to <see cref="Pan"/> cancels the effect of Apply3D.</para></remarks>
float Pan { get; set; }
/// <summary>
/// Gets or sets the pitch of the sound, might conflict with spatialized sound spatialization.
/// </summary>
float Pitch { get; set; }
/// <summary>
/// Applies 3D positioning to the sound.
/// More precisely adjust the channel volumes and pitch of the sound,
/// such that the sound source seems to come from the <paramref name="emitter"/> to the listener/>.
/// </summary>
/// <param name="emitter">The emitter that correspond to this sound</param>
/// <remarks>
/// <see cref="Apply3D"/> can be used only on mono-sounds.
/// <para>A call to <see cref="Apply3D"/> reset <see cref="Pan"/> to its default values.</para>
/// <para>A call to <see cref="Apply3D"/> does not modify the value of <see cref="IPlayableSound.Volume"/>,
/// the effective volume of the sound is a combination of the two effects.</para>
/// <para>
/// The final resulting pitch depends on the listener and emitter relative velocity.
/// The final resulting channel volumes depend on the listener and emitter relative positions and the value of <see cref="IPlayableSound.Volume"/>.
/// </para>
/// </remarks>
void Apply3D(AudioEmitter emitter);
}
}
| 57.403846 | 156 | 0.635176 | [
"MIT"
] | Aggror/Stride | sources/engine/Stride.Audio/IPositionableSound.cs | 2,985 | C# |
using System;
namespace BlizzardAPI.WoW{
public class MythicSeason{
public int id{get;set;}
public DateTime startDate{get;set;}
public DateTime? endDate{get;set;}
}
} | 22.111111 | 43 | 0.653266 | [
"MIT"
] | universal11/BlizzardAPI | WoW/MythicSeason.cs | 199 | C# |
using System;
using Microsoft.Owin;
using Unity;
namespace Owin.Localization.Unity
{
/// <summary>
/// Wrapper culture provider that resolves another type of provider using the owin request's lifetime scope during and forwards the determination to that provider
/// This allows for injecting in dependencies like shared cache or database connections, http clients etc using DI best practices
/// </summary>
/// <typeparam name="TCultureProvider"></typeparam>
internal class RequestCultureProviderInjectionAdapter<TCultureProvider> : RequestCultureProviderInjectionAdapterBase<TCultureProvider>
where TCultureProvider : IRequestCultureProvider
{
private readonly IUnityContainer unityContainer;
public RequestCultureProviderInjectionAdapter(IUnityContainer container)
{
this.unityContainer = container;
}
protected override TCultureProvider ResolveProvider(IOwinContext httpContext)
{
return this.unityContainer.Resolve<TCultureProvider>();
}
}
}
| 38.178571 | 166 | 0.737138 | [
"Apache-2.0"
] | pableess/Owin.Extensions.Localization | src/Owin.Unity/RequestCultureProviderInjectionAdapter.cs | 1,069 | C# |
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Balivo.AppCenterClient.Models
{
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// Event property value counts during the time range in descending order
/// </summary>
public partial class EventPropertyValues
{
/// <summary>
/// Initializes a new instance of the EventPropertyValues class.
/// </summary>
public EventPropertyValues()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the EventPropertyValues class.
/// </summary>
/// <param name="total">The total property value counts</param>
/// <param name="values">The event property values</param>
public EventPropertyValues(long? total = default(long?), IList<EventPropertyValue> values = default(IList<EventPropertyValue>))
{
Total = total;
Values = values;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets the total property value counts
/// </summary>
[JsonProperty(PropertyName = "total")]
public long? Total { get; set; }
/// <summary>
/// Gets or sets the event property values
/// </summary>
[JsonProperty(PropertyName = "values")]
public IList<EventPropertyValue> Values { get; set; }
}
}
| 30.913793 | 135 | 0.604016 | [
"MIT"
] | balivo/appcenter-openapi-sdk | generated/Models/EventPropertyValues.cs | 1,793 | C# |
using System.Collections.Generic;
using xnaMugen.Combat;
namespace xnaMugen.Evaluation.Triggers
{
[CustomFunction("HitDefAttr")]
internal static class HitDefAttr
{
public static bool Evaluate(Character character, ref bool error, Operator @operator, AttackStateType ast, Combat.HitType[] hittypes)
{
if (character == null)
{
error = true;
return false;
}
if (character.MoveType != xnaMugen.MoveType.Attack) return false;
var attr = character.OffensiveInfo.HitDef.HitAttribute;
var heightmatch = (attr.AttackHeight & ast) != AttackStateType.None;
var datamatch = false;
foreach (var hittype in hittypes)
{
if (attr.HasData(hittype) == false) continue;
datamatch = true;
break;
}
switch (@operator)
{
case Operator.Equals:
return heightmatch && datamatch;
case Operator.NotEquals:
return !heightmatch || !datamatch;
default:
error = true;
return false;
}
}
public static Node Parse(ParseState parsestate)
{
var @operator = parsestate.CurrentOperator;
if (@operator != Operator.Equals && @operator != Operator.NotEquals) return null;
parsestate.BaseNode.Arguments.Add(@operator);
++parsestate.TokenIndex;
var ast = parsestate.ConvertCurrentToken<AttackStateType>();
if (ast == AttackStateType.None) return null;
parsestate.BaseNode.Arguments.Add(ast);
++parsestate.TokenIndex;
var hittypes = new List<Combat.HitType>();
while (true)
{
if (parsestate.CurrentSymbol != Symbol.Comma) break;
++parsestate.TokenIndex;
var hittype = parsestate.ConvertCurrentToken<Combat.HitType?>();
if (hittype == null)
{
--parsestate.TokenIndex;
break;
}
hittypes.Add(hittype.Value);
++parsestate.TokenIndex;
}
parsestate.BaseNode.Arguments.Add(hittypes.ToArray());
return parsestate.BaseNode;
}
}
}
| 23.686747 | 135 | 0.657172 | [
"BSD-3-Clause"
] | BlazesRus/xnamugen | src/Evaluation/Triggers/HitDefAttr.cs | 1,968 | C# |
using System;
public class Program
{
public static void Main()
{
Book bookOne = new Book("Animal Farm", 1930, "George Orwell");
Book bookTwo = new Book("The Documents in the Case", 2002, "Dorothy Sayers", "Robert Eustace");
Book bookThree = new Book("The Documents in the Case", 2003);
var l = new Library(bookOne,bookTwo,bookThree);
BookComparator bc = new BookComparator();
}
} | 31 | 103 | 0.638249 | [
"Apache-2.0"
] | Warglaive/CSharp-OOP-Advanced | Iterators and Comparators - Lab/04.BookComparer/Program.cs | 436 | C# |
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Gov.Lclb.Cllb.Interfaces
{
using Microsoft.Rest;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Duplicaterecordidadoxiologin operations.
/// </summary>
public partial class Duplicaterecordidadoxiologin : IServiceOperations<DynamicsClient>, IDuplicaterecordidadoxiologin
{
/// <summary>
/// Initializes a new instance of the Duplicaterecordidadoxiologin class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public Duplicaterecordidadoxiologin(DynamicsClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the DynamicsClient
/// </summary>
public DynamicsClient Client { get; private set; }
/// <summary>
/// Get duplicaterecordid_adoxio_login from duplicaterecords
/// </summary>
/// <param name='duplicateid'>
/// key: duplicateid of duplicaterecord
/// </param>
/// <param name='select'>
/// Select properties to be returned
/// </param>
/// <param name='expand'>
/// Expand related entities
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<MicrosoftDynamicsCRMadoxioLogin>> GetWithHttpMessagesAsync(string duplicateid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (duplicateid == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "duplicateid");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("duplicateid", duplicateid);
tracingParameters.Add("select", select);
tracingParameters.Add("expand", expand);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "duplicaterecords({duplicateid})/duplicaterecordid_adoxio_login").ToString();
_url = _url.Replace("{duplicateid}", System.Uri.EscapeDataString(duplicateid));
List<string> _queryParameters = new List<string>();
if (select != null)
{
_queryParameters.Add(string.Format("$select={0}", System.Uri.EscapeDataString(string.Join(",", select))));
}
if (expand != null)
{
_queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(string.Join(",", expand))));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<MicrosoftDynamicsCRMadoxioLogin>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<MicrosoftDynamicsCRMadoxioLogin>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| 41.812207 | 341 | 0.569953 | [
"Apache-2.0"
] | BrendanBeachBC/jag-lcrb-carla-public | cllc-interfaces/Dynamics-Autorest/Duplicaterecordidadoxiologin.cs | 8,906 | C# |
using System;
namespace Koios.Core.Types
{
public class KBooleanType : KConcreteType
{
public override Type NativeType => typeof(bool);
public override string ToSerialized(object nativeValue)
{
return (nativeValue as bool?)?.ToString();
}
public override object ToNative(string serializedValue)
{
return bool.TryParse(serializedValue, out var nativeValue)
? (object)nativeValue
: null;
}
}
}
| 23.636364 | 70 | 0.592308 | [
"MIT"
] | jonrp/Koios | Koios.Core/Types/KBooleanType.cs | 522 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the ram-2018-01-04.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.RAM.Model
{
/// <summary>
/// A required input parameter is missing.
/// </summary>
#if !PCL && !NETSTANDARD
[Serializable]
#endif
public partial class MissingRequiredParameterException : AmazonRAMException
{
/// <summary>
/// Constructs a new MissingRequiredParameterException with the specified error
/// message.
/// </summary>
/// <param name="message">
/// Describes the error encountered.
/// </param>
public MissingRequiredParameterException(string message)
: base(message) {}
/// <summary>
/// Construct instance of MissingRequiredParameterException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
public MissingRequiredParameterException(string message, Exception innerException)
: base(message, innerException) {}
/// <summary>
/// Construct instance of MissingRequiredParameterException
/// </summary>
/// <param name="innerException"></param>
public MissingRequiredParameterException(Exception innerException)
: base(innerException) {}
/// <summary>
/// Construct instance of MissingRequiredParameterException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public MissingRequiredParameterException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, innerException, errorType, errorCode, requestId, statusCode) {}
/// <summary>
/// Construct instance of MissingRequiredParameterException
/// </summary>
/// <param name="message"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public MissingRequiredParameterException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, errorType, errorCode, requestId, statusCode) {}
#if !PCL && !NETSTANDARD
/// <summary>
/// Constructs a new instance of the MissingRequiredParameterException class with serialized data.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception>
/// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception>
protected MissingRequiredParameterException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
: base(info, context)
{
}
/// <summary>
/// Sets the <see cref="T:System.Runtime.Serialization.SerializationInfo" /> with information about the exception.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is a null reference (Nothing in Visual Basic). </exception>
#if BCL35
[System.Security.Permissions.SecurityPermission(
System.Security.Permissions.SecurityAction.LinkDemand,
Flags = System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter)]
#endif
[System.Security.SecurityCritical]
// These FxCop rules are giving false-positives for this method
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2134:MethodsMustOverrideWithConsistentTransparencyFxCopRule")]
public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
{
base.GetObjectData(info, context);
}
#endif
}
} | 47.927419 | 178 | 0.684335 | [
"Apache-2.0"
] | JeffAshton/aws-sdk-net | sdk/src/Services/RAM/Generated/Model/MissingRequiredParameterException.cs | 5,943 | C# |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Ads.GoogleAds.V7.Services.Snippets
{
using Google.Ads.GoogleAds.V7.Resources;
using Google.Ads.GoogleAds.V7.Services;
using System.Threading.Tasks;
public sealed partial class GeneratedAdGroupCriterionServiceClientStandaloneSnippets
{
/// <summary>Snippet for GetAdGroupCriterionAsync</summary>
/// <remarks>
/// This snippet has been automatically generated for illustrative purposes only.
/// It may require modifications to work in your environment.
/// </remarks>
public async Task GetAdGroupCriterionResourceNamesAsync()
{
// Create client
AdGroupCriterionServiceClient adGroupCriterionServiceClient = await AdGroupCriterionServiceClient.CreateAsync();
// Initialize request argument(s)
AdGroupCriterionName resourceName = AdGroupCriterionName.FromCustomerAdGroupCriterion("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[CRITERION_ID]");
// Make the request
AdGroupCriterion response = await adGroupCriterionServiceClient.GetAdGroupCriterionAsync(resourceName);
}
}
}
| 42.95122 | 150 | 0.721181 | [
"Apache-2.0"
] | googleapis/googleapis-gen | google/ads/googleads/v7/googleads-csharp/Google.Ads.GoogleAds.V7.Services.StandaloneSnippets/AdGroupCriterionServiceClient.GetAdGroupCriterionResourceNamesAsyncSnippet.g.cs | 1,761 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// Template Source: Templates\CSharp\Requests\IEntityRequestBuilder.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
/// <summary>
/// The interface IOfficeGraphInsightsRequestBuilder.
/// </summary>
public partial interface IOfficeGraphInsightsRequestBuilder : IEntityRequestBuilder
{
/// <summary>
/// Builds the request.
/// </summary>
/// <returns>The built request.</returns>
new IOfficeGraphInsightsRequest Request();
/// <summary>
/// Builds the request.
/// </summary>
/// <param name="options">The query and header options for the request.</param>
/// <returns>The built request.</returns>
new IOfficeGraphInsightsRequest Request(IEnumerable<Option> options);
/// <summary>
/// Gets the request builder for Trending.
/// </summary>
/// <returns>The <see cref="IOfficeGraphInsightsTrendingCollectionRequestBuilder"/>.</returns>
IOfficeGraphInsightsTrendingCollectionRequestBuilder Trending { get; }
/// <summary>
/// Gets the request builder for Shared.
/// </summary>
/// <returns>The <see cref="IOfficeGraphInsightsSharedCollectionRequestBuilder"/>.</returns>
IOfficeGraphInsightsSharedCollectionRequestBuilder Shared { get; }
/// <summary>
/// Gets the request builder for Used.
/// </summary>
/// <returns>The <see cref="IOfficeGraphInsightsUsedCollectionRequestBuilder"/>.</returns>
IOfficeGraphInsightsUsedCollectionRequestBuilder Used { get; }
}
}
| 39.150943 | 153 | 0.607711 | [
"MIT"
] | AzureMentor/msgraph-sdk-dotnet | src/Microsoft.Graph/Requests/Generated/IOfficeGraphInsightsRequestBuilder.cs | 2,075 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Build.Construction;
using Microsoft.Build.Definition;
using Microsoft.Build.Evaluation;
using Microsoft.Build.Evaluation.Context;
using Microsoft.Build.Execution;
using Microsoft.Build.Framework;
using Microsoft.Build.Graph;
using Microsoft.Build.Logging;
using NuGet.Commands;
using NuGet.Common;
using NuGet.Configuration;
using NuGet.Frameworks;
using NuGet.LibraryModel;
using NuGet.Packaging;
using NuGet.ProjectModel;
using NuGet.RuntimeModel;
using NuGet.Versioning;
namespace NuGet.Build.Tasks.Console
{
internal sealed class MSBuildStaticGraphRestore : IDisposable
{
private static readonly Lazy<IMachineWideSettings> MachineWideSettingsLazy = new Lazy<IMachineWideSettings>(() => new XPlatMachineWideSetting());
/// <summary>
/// Represents the small list of targets that must be executed in order for PackageReference, PackageDownload, and FrameworkReference items to be accurate.
/// </summary>
private static readonly string[] TargetsToBuild =
{
"CollectPackageReferences",
"CollectPackageDownloads",
"CollectFrameworkReferences",
"CollectCentralPackageVersions"
};
private readonly Lazy<ConsoleLoggingQueue> _loggingQueueLazy;
private readonly Lazy<MSBuildLogger> _msBuildLoggerLazy;
private readonly SettingsLoadingContext _settingsLoadContext = new SettingsLoadingContext();
public MSBuildStaticGraphRestore(bool debug = false)
{
Debug = debug;
_loggingQueueLazy = new Lazy<ConsoleLoggingQueue>(() => new ConsoleLoggingQueue(LoggerVerbosity.Normal));
_msBuildLoggerLazy = new Lazy<MSBuildLogger>(() => new MSBuildLogger(LoggingQueue.TaskLoggingHelper));
}
/// <summary>
/// Gets or sets a value indicating if this application is being debugged.
/// </summary>
public bool Debug { get; }
/// <summary>
/// Gets a <see cref="ConsoleLoggingQueue" /> object to be used for logging.
/// </summary>
private ConsoleLoggingQueue LoggingQueue => _loggingQueueLazy.Value;
/// <summary>
/// Gets a <see cref="MSBuildLogger" /> object to be used for logging.
/// </summary>
private MSBuildLogger MSBuildLogger => _msBuildLoggerLazy.Value;
public void Dispose()
{
if (_loggingQueueLazy.IsValueCreated)
{
// Disposing the logging queue will wait for the queue to be drained
_loggingQueueLazy.Value.Dispose();
}
_settingsLoadContext.Dispose();
}
/// <summary>
/// Restores the specified projects.
/// </summary>
/// <param name="entryProjectFilePath">The main project to restore. This can be a project for a Visual Studio© Solution File.</param>
/// <param name="globalProperties">The global properties to use when evaluation MSBuild projects.</param>
/// <param name="options">The set of options to use when restoring. These options come from the main MSBuild process and control how restore functions.</param>
/// <returns><code>true</code> if the restore succeeded, otherwise <code>false</code>.</returns>
[MethodImpl(MethodImplOptions.NoInlining)]
public async Task<bool> RestoreAsync(string entryProjectFilePath, IDictionary<string, string> globalProperties, IReadOnlyDictionary<string, string> options)
{
var dependencyGraphSpec = GetDependencyGraphSpec(entryProjectFilePath, globalProperties);
// If the dependency graph spec is null, something went wrong evaluating the projects, so return false
if (dependencyGraphSpec == null)
{
return false;
}
try
{
return await BuildTasksUtility.RestoreAsync(
dependencyGraphSpec: dependencyGraphSpec,
interactive: IsOptionTrue(nameof(RestoreTaskEx.Interactive), options),
recursive: IsOptionTrue(nameof(RestoreTaskEx.Recursive), options),
noCache: IsOptionTrue(nameof(RestoreTaskEx.NoCache), options),
ignoreFailedSources: IsOptionTrue(nameof(RestoreTaskEx.IgnoreFailedSources), options),
disableParallel: IsOptionTrue(nameof(RestoreTaskEx.DisableParallel), options),
force: IsOptionTrue(nameof(RestoreTaskEx.Force), options),
forceEvaluate: IsOptionTrue(nameof(RestoreTaskEx.ForceEvaluate), options),
hideWarningsAndErrors: IsOptionTrue(nameof(RestoreTaskEx.HideWarningsAndErrors), options),
restorePC: IsOptionTrue(nameof(RestoreTaskEx.RestorePackagesConfig), options),
cleanupAssetsForUnsupportedProjects: IsOptionTrue(nameof(RestoreTaskEx.CleanupAssetsForUnsupportedProjects), options),
log: MSBuildLogger,
cancellationToken: CancellationToken.None);
}
catch (Exception e)
{
LoggingQueue.TaskLoggingHelper.LogErrorFromException(e, showStackTrace: true);
return false;
}
}
/// <summary>
/// Generates a dependency graph spec for the given properties.
/// </summary>
/// <param name="entryProjectFilePath">The main project to generate that graph for. This can be a project for a Visual Studio© Solution File.</param>
/// <param name="globalProperties">The global properties to use when evaluation MSBuild projects.</param>
/// <param name="options">The set of options to use to generate the graph, including the restore graph output path.</param>
/// <returns><code>true</code> if the dependency graph spec was generated and written, otherwise <code>false</code>.</returns>
public bool WriteDependencyGraphSpec(string entryProjectFilePath, IDictionary<string, string> globalProperties, IReadOnlyDictionary<string, string> options)
{
var dependencyGraphSpec = GetDependencyGraphSpec(entryProjectFilePath, globalProperties);
try
{
if (dependencyGraphSpec == null)
{
LoggingQueue.TaskLoggingHelper.LogError(Strings.Error_DgSpecGenerationFailed);
return false;
}
if (options.TryGetValue("RestoreGraphOutputPath", out var path))
{
dependencyGraphSpec.Save(path);
return true;
}
else
{
LoggingQueue.TaskLoggingHelper.LogError(Strings.Error_MissingRestoreGraphOutputPath);
}
}
catch (Exception e)
{
LoggingQueue.TaskLoggingHelper.LogErrorFromException(e, showStackTrace: true);
}
return false;
}
/// <summary>
/// Gets the framework references per target framework for the specified project.
/// </summary>
/// <param name="project">The <see cref="ProjectInstance" /> to get framework references for.</param>
/// <returns>A <see cref="List{FrameworkDependency}" /> containing the framework references for the specified project.</returns>
internal static List<FrameworkDependency> GetFrameworkReferences(IMSBuildProject project)
{
// Get the unique FrameworkReference items, ignoring duplicates
List<IMSBuildItem> frameworkReferenceItems = GetDistinctItemsOrEmpty(project, "FrameworkReference").ToList();
// For best performance, its better to create a list with the exact number of items needed rather than using a LINQ statement or AddRange. This is because if the list
// is not allocated with enough items, the list has to be grown which can slow things down
var frameworkDependencies = new List<FrameworkDependency>(frameworkReferenceItems.Count);
foreach (var frameworkReferenceItem in frameworkReferenceItems)
{
var privateAssets = MSBuildStringUtility.Split(frameworkReferenceItem.GetProperty("PrivateAssets"));
frameworkDependencies.Add(new FrameworkDependency(frameworkReferenceItem.Identity, FrameworkDependencyFlagsUtils.GetFlags(privateAssets)));
}
return frameworkDependencies;
}
/// <summary>
/// Gets the package downloads for the specified project.
/// </summary>
/// <param name="project">The <see cref="ProjectInstance" /> to get package downloads for.</param>
/// <returns>An <see cref="IEnumerable{DownloadDependency}" /> containing the package downloads for the specified project.</returns>
internal static IEnumerable<DownloadDependency> GetPackageDownloads(IMSBuildProject project)
{
// Get the distinct PackageDownload items, ignoring duplicates
foreach (IMSBuildItem projectItemInstance in GetDistinctItemsOrEmpty(project, "PackageDownload"))
{
string id = projectItemInstance.Identity;
// PackageDownload items can contain multiple versions
foreach (var version in MSBuildStringUtility.Split(projectItemInstance.GetProperty("Version")))
{
// Validate the version range
VersionRange versionRange = !string.IsNullOrWhiteSpace(version) ? VersionRange.Parse(version) : VersionRange.All;
if (!(versionRange.HasLowerAndUpperBounds && versionRange.MinVersion.Equals(versionRange.MaxVersion)))
{
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Strings.Error_PackageDownload_OnlyExactVersionsAreAllowed, versionRange.OriginalString));
}
yield return new DownloadDependency(id, versionRange);
}
}
}
/// <summary>
/// Gets the centrally defined package version information.
/// </summary>
/// <param name="project">The <see cref="ProjectInstance" /> to get PackageVersion for.</param>
/// <returns>An <see cref="IEnumerable{CentralPackageVersion}" /> containing the package versions for the specified project.</returns>
internal static Dictionary<string, CentralPackageVersion> GetCentralPackageVersions(IMSBuildProject project)
{
var result = new Dictionary<string, CentralPackageVersion>();
IEnumerable<IMSBuildItem> packageVersionItems = GetDistinctItemsOrEmpty(project, "PackageVersion");
foreach (var projectItemInstance in packageVersionItems)
{
string id = projectItemInstance.Identity;
string version = projectItemInstance.GetProperty("Version");
VersionRange versionRange = string.IsNullOrWhiteSpace(version) ? VersionRange.All : VersionRange.Parse(version);
result.Add(id, new CentralPackageVersion(id, versionRange));
}
return result;
}
/// <summary>
/// Gets the package references for the specified project.
/// </summary>
/// <param name="project">The <see cref="ProjectInstance" /> to get package references for.</param>
/// <param name="isCentralPackageVersionManagementEnabled">A flag for central package version management being enabled.</param>
/// <returns>A <see cref="List{LibraryDependency}" /> containing the package references for the specified project.</returns>
internal static List<LibraryDependency> GetPackageReferences(IMSBuildProject project, bool isCentralPackageVersionManagementEnabled)
{
// Get the distinct PackageReference items, ignoring duplicates
List<IMSBuildItem> packageReferenceItems = GetDistinctItemsOrEmpty(project, "PackageReference").ToList();
var libraryDependencies = new List<LibraryDependency>(packageReferenceItems.Count);
foreach (var packageReferenceItem in packageReferenceItems)
{
string version = packageReferenceItem.GetProperty("Version");
libraryDependencies.Add(new LibraryDependency
{
AutoReferenced = packageReferenceItem.IsPropertyTrue("IsImplicitlyDefined"),
GeneratePathProperty = packageReferenceItem.IsPropertyTrue("GeneratePathProperty"),
Aliases = packageReferenceItem.GetProperty("Aliases"),
IncludeType = GetLibraryIncludeFlags(packageReferenceItem.GetProperty("IncludeAssets"), LibraryIncludeFlags.All) & ~GetLibraryIncludeFlags(packageReferenceItem.GetProperty("ExcludeAssets"), LibraryIncludeFlags.None),
LibraryRange = new LibraryRange(
packageReferenceItem.Identity,
string.IsNullOrWhiteSpace(version) ? isCentralPackageVersionManagementEnabled ? null : VersionRange.All : VersionRange.Parse(version),
LibraryDependencyTarget.Package),
NoWarn = MSBuildStringUtility.GetNuGetLogCodes(packageReferenceItem.GetProperty("NoWarn")).ToList(),
SuppressParent = GetLibraryIncludeFlags(packageReferenceItem.GetProperty("PrivateAssets"), LibraryIncludeFlagUtils.DefaultSuppressParent)
});
}
return libraryDependencies;
}
/// <summary>
/// Gets the packages path for the specified project.
/// </summary>
/// <param name="project">The <see cref="IMSBuildItem" /> representing the project.</param>
/// <param name="settings">The <see cref="ISettings" /> of the project.</param>
/// <returns>The full path to the packages directory for the specified project.</returns>
internal static string GetPackagesPath(IMSBuildProject project, ISettings settings)
{
return RestoreSettingsUtils.GetValue(
() => UriUtility.GetAbsolutePath(project.Directory, project.GetGlobalProperty("RestorePackagesPath")),
() => UriUtility.GetAbsolutePath(project.Directory, project.GetProperty("RestorePackagesPath")),
() => SettingsUtility.GetGlobalPackagesFolder(settings));
}
/// <summary>
/// Gets the name of the specified project.
/// </summary>
/// <param name="project">The <see cref="IMSBuildItem" /> representing the project.</param>
/// <returns>The name of the specified project.</returns>
internal static string GetProjectName(IMSBuildProject project)
{
string packageId = project.GetProperty("PackageId");
if (!string.IsNullOrWhiteSpace(packageId))
{
// If the PackageId property was specified, return that
return packageId;
}
string assemblyName = project.GetProperty("AssemblyName");
if (!string.IsNullOrWhiteSpace(assemblyName))
{
// If the AssemblyName property was specified, return that
return assemblyName;
}
// By default return the MSBuildProjectName which is a built-in property that represents the name of the project file without the file extension
return project.GetProperty("MSBuildProjectName");
}
/// <summary>
/// Gets the project references of the specified project.
/// </summary>
/// <param name="project">The <see cref="ProjectInstance" /> to get project references for.</param>
/// <returns>A <see cref="List{ProjectRestoreReference}" /> containing the project references for the specified project.</returns>
internal static List<ProjectRestoreReference> GetProjectReferences(IMSBuildProject project)
{
// Get the unique list of ProjectReference items that have the ReferenceOutputAssembly metadata set to "true", ignoring duplicates
var projectReferenceItems = project.GetItems("ProjectReference")
.Where(i => i.IsPropertyTrue("ReferenceOutputAssembly", defaultValue: true))
.Distinct(ProjectItemInstanceEvaluatedIncludeComparer.Instance)
.ToList();
var projectReferences = new List<ProjectRestoreReference>(projectReferenceItems.Count);
foreach (var projectReferenceItem in projectReferenceItems)
{
string fullPath = projectReferenceItem.GetProperty("FullPath");
projectReferences.Add(new ProjectRestoreReference
{
ExcludeAssets = GetLibraryIncludeFlags(projectReferenceItem.GetProperty("ExcludeAssets"), LibraryIncludeFlags.None),
IncludeAssets = GetLibraryIncludeFlags(projectReferenceItem.GetProperty("IncludeAssets"), LibraryIncludeFlags.All),
PrivateAssets = GetLibraryIncludeFlags(projectReferenceItem.GetProperty("PrivateAssets"), LibraryIncludeFlagUtils.DefaultSuppressParent),
ProjectPath = fullPath,
ProjectUniqueName = fullPath
});
}
return projectReferences;
}
/// <summary>
/// Gets the restore metadata framework information for the specified projects.
/// </summary>
/// <param name="projects">A <see cref="IReadOnlyDictionary{NuGetFramework,ProjectInstance}" /> representing the target frameworks and their corresponding projects.</param>
/// <returns>A <see cref="List{ProjectRestoreMetadataFrameworkInfo}" /> containing the restore metadata framework information for the specified project.</returns>
internal static List<ProjectRestoreMetadataFrameworkInfo> GetProjectRestoreMetadataFrameworkInfos(List<TargetFrameworkInformation> targetFrameworkInfos, IReadOnlyDictionary<string, IMSBuildProject> projects)
{
var projectRestoreMetadataFrameworkInfos = new List<ProjectRestoreMetadataFrameworkInfo>(projects.Count);
foreach (var targetFrameworkInfo in targetFrameworkInfos)
{
var project = projects[targetFrameworkInfo.TargetAlias];
projectRestoreMetadataFrameworkInfos.Add(new ProjectRestoreMetadataFrameworkInfo(targetFrameworkInfo.FrameworkName)
{
TargetAlias = targetFrameworkInfo.TargetAlias,
ProjectReferences = GetProjectReferences(project)
});
}
return projectRestoreMetadataFrameworkInfos;
}
/// <summary>
/// Gets the target frameworks for the specified project.
/// </summary>
/// <param name="project">An <see cref="IMSBuildProject" /> representing the main project.</param>
/// <param name="innerNodes">An <see cref="IReadOnlyDictionary{String,IMSBuildProject}" /> representing all inner projects by their target framework.</param>
/// <returns></returns>
internal static IReadOnlyDictionary<string, IMSBuildProject> GetProjectTargetFrameworks(IMSBuildProject project, IReadOnlyDictionary<string, IMSBuildProject> innerNodes)
{
var projectFrameworkStrings = GetTargetFrameworkStrings(project);
var projectTargetFrameworks = new Dictionary<string, IMSBuildProject>();
if (projectFrameworkStrings.Length > 0)
{
foreach (var projectTargetFramework in projectFrameworkStrings)
{
// Attempt to get the corresponding project instance for the target framework. If one is not found, then the project must not target multiple frameworks
// and the main project should be used
if (!innerNodes.TryGetValue(projectTargetFramework, out IMSBuildProject innerNode))
{
innerNode = project;
}
// Add the target framework and associate it with the project instance to be used for gathering details
projectTargetFrameworks[projectTargetFramework] = innerNode;
}
}
else
{
// Attempt to get the corresponding project instance for the target framework. If one is not found, then the project must not target multiple frameworks
// and the main project should be used
projectTargetFrameworks[string.Empty] = project;
}
return projectTargetFrameworks;
}
internal static string[] GetTargetFrameworkStrings(IMSBuildProject project)
{
var targetFrameworks = project.GetProperty("TargetFrameworks");
if (string.IsNullOrEmpty(targetFrameworks))
{
targetFrameworks = project.GetProperty("TargetFramework");
}
var projectFrameworkStrings = MSBuildStringUtility.Split(targetFrameworks);
return projectFrameworkStrings;
}
/// <summary>
/// Gets the version of the project.
/// </summary>
/// <param name="project">The <see cref="IMSBuildItem" /> representing the project.</param>
/// <returns>The <see cref="NuGetVersion" /> of the specified project if one was found, otherwise <see cref="PackageSpec.DefaultVersion" />.</returns>
internal static NuGetVersion GetProjectVersion(IMSBuildItem project)
{
string version = project.GetProperty("PackageVersion") ?? project.GetProperty("Version");
if (version == null)
{
return PackageSpec.DefaultVersion;
}
return NuGetVersion.Parse(version);
}
/// <summary>
/// Gets the repository path for the specified project.
/// </summary>
/// <param name="project">The <see cref="IMSBuildItem" /> representing the project.</param>
/// <param name="settings">The <see cref="ISettings" /> of the specified project.</param>
/// <returns>The repository path of the specified project.</returns>
internal static string GetRepositoryPath(IMSBuildProject project, ISettings settings)
{
return RestoreSettingsUtils.GetValue(
() => UriUtility.GetAbsolutePath(project.Directory, project.GetGlobalProperty("RestoreRepositoryPath")),
() => UriUtility.GetAbsolutePath(project.Directory, project.GetProperty("RestoreRepositoryPath")),
() => SettingsUtility.GetRepositoryPath(settings),
() =>
{
string solutionDir = project.GetProperty("SolutionPath");
solutionDir = string.Equals(solutionDir, "*Undefined*", StringComparison.OrdinalIgnoreCase)
? project.Directory
: Path.GetDirectoryName(solutionDir);
return UriUtility.GetAbsolutePath(solutionDir, PackagesConfig.PackagesNodeName);
});
}
/// <summary>
/// Gets the restore output path for the specified project.
/// </summary>
/// <param name="project">The <see cref="IMSBuildItem" /> representing the project.</param>
/// <returns>The full path to the restore output directory for the specified project if a value is specified, otherwise <code>null</code>.</returns>
internal static string GetRestoreOutputPath(IMSBuildProject project)
{
string outputPath = project.GetProperty("RestoreOutputPath") ?? project.GetProperty("MSBuildProjectExtensionsPath");
return outputPath == null ? null : Path.GetFullPath(Path.Combine(project.Directory, outputPath));
}
/// <summary>
/// Gets the package sources of the specified project.
/// </summary>
/// <param name="project">An <see cref="IMSBuildItem" /> representing the project..</param>
/// <param name="innerNodes">An <see cref="IReadOnlyCollection{IMSBuildItem}" /> containing the inner nodes of the project if its targets multiple frameworks.</param>
/// <param name="settings">The <see cref="ISettings" /> of the specified project.</param>
/// <returns>A <see cref="List{PackageSource}" /> object containing the packages sources for the specified project.</returns>
internal static List<PackageSource> GetSources(IMSBuildProject project, IReadOnlyCollection<IMSBuildProject> innerNodes, ISettings settings)
{
return BuildTasksUtility.GetSources(
project.GetGlobalProperty("OriginalMSBuildStartupDirectory"),
project.Directory,
project.SplitPropertyValueOrNull("RestoreSources"),
project.SplitGlobalPropertyValueOrNull("RestoreSources"),
innerNodes.SelectMany(i => MSBuildStringUtility.Split(i.GetProperty("RestoreAdditionalProjectSources"))),
settings)
.Select(i => new PackageSource(i))
.ToList();
}
/// <summary>
/// Gets a value indicating if the specified project is a legacy project.
/// </summary>
/// <param name="project">The <see cref="IMSBuildItem" /> representing the project.</param>
/// <returns><code>true</code> if the specified project is considered legacy, otherwise <code>false</code>.</returns>
internal static bool IsLegacyProject(IMSBuildItem project)
{
// We consider the project to be legacy if it does not specify TargetFramework or TargetFrameworks
return project.GetProperty("TargetFramework") == null && project.GetProperty("TargetFrameworks") == null;
}
/// <summary>
/// Determines of the specified option is <code>true</code>.
/// </summary>
/// <param name="name">The name of the option.</param>
/// <param name="options">A <see cref="Dictionary{String,String}" />containing options.</param>
/// <returns><code>true</code> if the specified option is true, otherwise <code>false</code>.</returns>
internal static bool IsOptionTrue(string name, IReadOnlyDictionary<string, string> options)
{
return options.TryGetValue(name, out string value) && StringComparer.OrdinalIgnoreCase.Equals(value, bool.TrueString);
}
/// <summary>
/// Gets the <see cref="LibraryIncludeFlags" /> for the specified value.
/// </summary>
/// <param name="value">A semicolon delimited list of include flags.</param>
/// <param name="defaultValue">The default value ot return if the value contains no flags.</param>
/// <returns>The <see cref="LibraryIncludeFlags" /> for the specified value, otherwise the <paramref name="defaultValue" />.</returns>
private static LibraryIncludeFlags GetLibraryIncludeFlags(string value, LibraryIncludeFlags defaultValue)
{
if (string.IsNullOrWhiteSpace(value))
{
return defaultValue;
}
string[] parts = MSBuildStringUtility.Split(value);
return parts.Length > 0 ? LibraryIncludeFlagUtils.GetFlags(parts) : defaultValue;
}
/// <summary>
/// Gets the list of project graph entry points. If the entry project is a solution, this method returns all of the projects it contains.
/// </summary>
/// <param name="entryProjectPath">The full path to the main project or solution file.</param>
/// <param name="globalProperties">An <see cref="IDictionary{String,String}" /> representing the global properties for the project.</param>
/// <returns></returns>
private static List<ProjectGraphEntryPoint> GetProjectGraphEntryPoints(string entryProjectPath, IDictionary<string, string> globalProperties)
{
// If the project's extension is .sln, parse it as a Visual Studio solution and return the projects it contains
if (string.Equals(Path.GetExtension(entryProjectPath), ".sln", StringComparison.OrdinalIgnoreCase))
{
var solutionFile = SolutionFile.Parse(entryProjectPath);
return solutionFile.ProjectsInOrder.Where(i => i.ProjectType == SolutionProjectType.KnownToBeMSBuildFormat).Select(i => new ProjectGraphEntryPoint(i.AbsolutePath, globalProperties)).ToList();
}
// Return just the main project in a list if its not a solution file
return new List<ProjectGraphEntryPoint>
{
new ProjectGraphEntryPoint(entryProjectPath, globalProperties),
};
}
/// <summary>
/// Gets the target framework information for the specified project. This includes the package references, package downloads, and framework references.
/// </summary>
/// <param name="projectInnerNodes">An <see cref="IReadOnlyDictionary{NuGetFramework,ProjectInstance} "/> containing the projects by their target framework.</param>
/// <param name="isCpvmEnabled">A flag that is true if the Central Package Management was enabled.</param>
/// <returns>A <see cref="List{TargetFrameworkInformation}" /> containing the target framework information for the specified project.</returns>
internal static List<TargetFrameworkInformation> GetTargetFrameworkInfos(IReadOnlyDictionary<string, IMSBuildProject> projectInnerNodes, bool isCpvmEnabled)
{
var targetFrameworkInfos = new List<TargetFrameworkInformation>(projectInnerNodes.Count);
foreach (var projectInnerNode in projectInnerNodes)
{
var msBuildProjectInstance = projectInnerNode.Value;
var targetAlias = string.IsNullOrEmpty(projectInnerNode.Key) ? string.Empty : projectInnerNode.Key;
NuGetFramework targetFramework = MSBuildProjectFrameworkUtility.GetProjectFramework(
projectFilePath: projectInnerNode.Value.FullPath,
targetFrameworkMoniker: msBuildProjectInstance.GetProperty("TargetFrameworkMoniker"),
targetPlatformMoniker: msBuildProjectInstance.GetProperty("TargetPlatformMoniker"),
targetPlatformMinVersion: msBuildProjectInstance.GetProperty("TargetPlatformMinVersion"));
var targetFrameworkInformation = new TargetFrameworkInformation()
{
FrameworkName = targetFramework,
TargetAlias = targetAlias,
RuntimeIdentifierGraphPath = msBuildProjectInstance.GetProperty(nameof(TargetFrameworkInformation.RuntimeIdentifierGraphPath))
};
var packageTargetFallback = MSBuildStringUtility.Split(msBuildProjectInstance.GetProperty("PackageTargetFallback")).Select(NuGetFramework.Parse).ToList();
var assetTargetFallback = MSBuildStringUtility.Split(msBuildProjectInstance.GetProperty(nameof(TargetFrameworkInformation.AssetTargetFallback))).Select(NuGetFramework.Parse).ToList();
AssetTargetFallbackUtility.EnsureValidFallback(packageTargetFallback, assetTargetFallback, msBuildProjectInstance.FullPath);
AssetTargetFallbackUtility.ApplyFramework(targetFrameworkInformation, packageTargetFallback, assetTargetFallback);
targetFrameworkInformation.Dependencies.AddRange(GetPackageReferences(msBuildProjectInstance, isCpvmEnabled));
targetFrameworkInformation.DownloadDependencies.AddRange(GetPackageDownloads(msBuildProjectInstance));
targetFrameworkInformation.FrameworkReferences.AddRange(GetFrameworkReferences(msBuildProjectInstance));
if (isCpvmEnabled && targetFrameworkInformation.Dependencies.Any())
{
targetFrameworkInformation.CentralPackageVersions.AddRange(GetCentralPackageVersions(msBuildProjectInstance));
LibraryDependency.ApplyCentralVersionInformation(targetFrameworkInformation.Dependencies, targetFrameworkInformation.CentralPackageVersions);
}
targetFrameworkInfos.Add(targetFrameworkInformation);
}
return targetFrameworkInfos;
}
/// <summary>
/// Gets a <see cref="DependencyGraphSpec" /> for the specified project.
/// </summary>
/// <param name="entryProjectPath">The full path to a project or Visual Studio Solution File.</param>
/// <param name="globalProperties">An <see cref="IDictionary{String,String}" /> containing the global properties to use when evaluation MSBuild projects.</param>
/// <returns>A <see cref="DependencyGraphSpec" /> for the specified project if they could be loaded, otherwise <code>null</code>.</returns>
private DependencyGraphSpec GetDependencyGraphSpec(string entryProjectPath, IDictionary<string, string> globalProperties)
{
try
{
MSBuildLogger.LogMinimal(Strings.DeterminingProjectsToRestore);
var entryProjects = GetProjectGraphEntryPoints(entryProjectPath, globalProperties);
// Load the projects via MSBuild and create an array of them since Parallel.ForEach is optimized for arrays
var projects = LoadProjects(entryProjects)?.ToArray();
// If no projects were loaded, return null indicating that the projects could not be loaded.
if (projects == null || projects.Length == 0)
{
return null;
}
var sw = Stopwatch.StartNew();
var dependencyGraphSpec = new DependencyGraphSpec(isReadOnly: true);
// Unique names created by the MSBuild restore target are project paths, these
// can be different on case-insensitive file systems for the same project file.
// To workaround this unique names should be compared based on the OS.
var uniqueNameComparer = PathUtility.GetStringComparerBasedOnOS();
var projectPathLookup = new ConcurrentDictionary<string, string>(uniqueNameComparer);
try
{
// Get the PackageSpecs in parallel because creating each one is relatively expensive so parallelism speeds things up
Parallel.ForEach(projects, new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount }, project =>
{
var packageSpec = GetPackageSpec(project.OuterProject, project);
if (packageSpec != null)
{
// Keep track of all project path casings
var uniqueName = packageSpec.RestoreMetadata.ProjectUniqueName;
if (uniqueName != null && !projectPathLookup.ContainsKey(uniqueName))
{
projectPathLookup.TryAdd(uniqueName, uniqueName);
}
var projectPath = packageSpec.RestoreMetadata.ProjectPath;
if (projectPath != null && !projectPathLookup.ContainsKey(projectPath))
{
projectPathLookup.TryAdd(projectPath, projectPath);
}
lock (dependencyGraphSpec)
{
dependencyGraphSpec.AddProject(packageSpec);
}
}
});
}
catch (AggregateException e)
{
// Log exceptions thrown while creating PackageSpec objects
foreach (var exception in e.Flatten().InnerExceptions)
{
LoggingQueue.TaskLoggingHelper.LogErrorFromException(exception);
}
return null;
}
// Fix project reference casings to match the original project on case insensitive file systems.
MSBuildRestoreUtility.NormalizePathCasings(projectPathLookup, dependencyGraphSpec);
// Add all entry projects if they support restore. In most cases this is just a single project but if the entry
// project is a solution, then all projects in the solution are added (if they support restore)
foreach (var entryPoint in entryProjects)
{
PackageSpec project = dependencyGraphSpec.GetProjectSpec(entryPoint.ProjectFile);
if (project != null && BuildTasksUtility.DoesProjectSupportRestore(project))
{
dependencyGraphSpec.AddRestore(entryPoint.ProjectFile);
}
}
sw.Stop();
MSBuildLogger.LogDebug(string.Format(CultureInfo.CurrentCulture, Strings.CreatedDependencyGraphSpec, sw.ElapsedMilliseconds));
return dependencyGraphSpec;
}
catch (Exception e)
{
LoggingQueue.TaskLoggingHelper.LogErrorFromException(e, showStackTrace: true);
}
return null;
}
/// <summary>
/// Gets a <see cref="PackageSpec" /> for the specified project.
/// </summary>
/// <param name="project">An <see cref="IMSBuildProject" /> object that represents the project.</param>
/// <param name="allInnerNodes">An <see cref="IReadOnlyDictionary{String,IMSBuildProject}" /> that represents all inner projects by their target framework.</param>
/// <returns></returns>
private PackageSpec GetPackageSpec(IMSBuildProject project, IReadOnlyDictionary<string, IMSBuildProject> allInnerNodes)
{
var settings = RestoreSettingsUtils.ReadSettings(
project.GetProperty("RestoreSolutionDirectory"),
project.GetProperty("RestoreRootConfigDirectory") ?? project.Directory,
UriUtility.GetAbsolutePath(project.Directory, project.GetProperty("RestoreConfigFile")),
MachineWideSettingsLazy,
_settingsLoadContext);
// Get the target frameworks for the project and the project instance for each framework
var projectsByTargetFramework = GetProjectTargetFrameworks(project, allInnerNodes);
(ProjectRestoreMetadata restoreMetadata, List<TargetFrameworkInformation> targetFrameworkInfos) = GetProjectRestoreMetadataAndTargetFrameworkInformation(project, projectsByTargetFramework, settings);
if (restoreMetadata == null || targetFrameworkInfos == null)
{
return null;
}
var packageSpec = new PackageSpec(targetFrameworkInfos)
{
FilePath = project.FullPath,
Name = restoreMetadata.ProjectName,
RestoreMetadata = restoreMetadata,
RuntimeGraph = new RuntimeGraph(
MSBuildStringUtility.Split($"{project.GetProperty("RuntimeIdentifiers")};{project.GetProperty("RuntimeIdentifier")}")
.Concat(projectsByTargetFramework.Values.SelectMany(i => MSBuildStringUtility.Split($"{i.GetProperty("RuntimeIdentifiers")};{i.GetProperty("RuntimeIdentifier")}")))
.Distinct(StringComparer.Ordinal)
.Select(rid => new RuntimeDescription(rid))
.ToList(),
MSBuildStringUtility.Split(project.GetProperty("RuntimeSupports"))
.Distinct(StringComparer.Ordinal)
.Select(s => new CompatibilityProfile(s))
.ToList()
),
Version = GetProjectVersion(project)
};
return packageSpec;
}
/// <summary>
/// Gets the restore metadata and target framework information for the specified project.
/// </summary>
/// <param name="project">An <see cref="IMSBuildProject" /> representing the project.</param>
/// <param name="projectsByTargetFramework">A <see cref="IReadOnlyDictionary{NuGetFramework,IMSBuildProject}" /> containing the inner nodes by target framework.</param>
/// <param name="settings">The <see cref="ISettings" /> of the specified project.</param>
/// <returns>A <see cref="Tuple" /> containing the <see cref="ProjectRestoreMetadata" /> and <see cref="List{TargetFrameworkInformation}" /> for the specified project.</returns>
private (ProjectRestoreMetadata RestoreMetadata, List<TargetFrameworkInformation> TargetFrameworkInfos) GetProjectRestoreMetadataAndTargetFrameworkInformation(IMSBuildProject project, IReadOnlyDictionary<string, IMSBuildProject> projectsByTargetFramework, ISettings settings)
{
var projectName = GetProjectName(project);
var outputPath = GetRestoreOutputPath(project);
var projectStyleOrNull = BuildTasksUtility.GetProjectRestoreStyleFromProjectProperty(project.GetProperty("RestoreProjectStyle"));
var isCpvmEnabled = IsCentralVersionsManagementEnabled(project, projectStyleOrNull);
var targetFrameworkInfos = GetTargetFrameworkInfos(projectsByTargetFramework, isCpvmEnabled);
var projectStyleResult = BuildTasksUtility.GetProjectRestoreStyle(
restoreProjectStyle: projectStyleOrNull,
hasPackageReferenceItems: targetFrameworkInfos.Any(i => i.Dependencies.Any()),
projectJsonPath: project.GetProperty("_CurrentProjectJsonPath"),
projectDirectory: project.Directory,
projectName: project.GetProperty("MSBuildProjectName"),
log: MSBuildLogger);
var projectStyle = projectStyleResult.ProjectStyle;
var innerNodes = projectsByTargetFramework.Values.ToList();
ProjectRestoreMetadata restoreMetadata;
if (projectStyle == ProjectStyle.PackagesConfig)
{
restoreMetadata = new PackagesConfigProjectRestoreMetadata
{
PackagesConfigPath = projectStyleResult.PackagesConfigFilePath,
RepositoryPath = GetRepositoryPath(project, settings)
};
}
else
{
restoreMetadata = new ProjectRestoreMetadata
{
// CrossTargeting is on, even if the TargetFrameworks property has only 1 tfm.
CrossTargeting = (projectStyle == ProjectStyle.PackageReference || projectStyle == ProjectStyle.DotnetToolReference) && (
projectsByTargetFramework.Count > 1 || !string.IsNullOrWhiteSpace(project.GetProperty("TargetFrameworks"))),
FallbackFolders = BuildTasksUtility.GetFallbackFolders(
project.GetProperty("MSBuildStartupDirectory"),
project.Directory,
project.SplitPropertyValueOrNull("RestoreFallbackFolders"),
project.SplitGlobalPropertyValueOrNull("RestoreFallbackFolders"),
innerNodes.SelectMany(i => MSBuildStringUtility.Split(i.GetProperty("RestoreAdditionalProjectFallbackFolders"))),
innerNodes.SelectMany(i => MSBuildStringUtility.Split(i.GetProperty("RestoreAdditionalProjectFallbackFoldersExcludes"))),
settings),
SkipContentFileWrite = IsLegacyProject(project),
ValidateRuntimeAssets = project.IsPropertyTrue("ValidateRuntimeIdentifierCompatibility"),
CentralPackageVersionsEnabled = isCpvmEnabled && projectStyle == ProjectStyle.PackageReference
};
}
restoreMetadata.CacheFilePath = NoOpRestoreUtilities.GetProjectCacheFilePath(outputPath, project.FullPath);
restoreMetadata.ConfigFilePaths = settings.GetConfigFilePaths();
restoreMetadata.OutputPath = outputPath;
targetFrameworkInfos.ForEach(tfi =>
restoreMetadata.OriginalTargetFrameworks.Add(
!string.IsNullOrEmpty(tfi.TargetAlias) ?
tfi.TargetAlias :
tfi.FrameworkName.GetShortFolderName()));
restoreMetadata.PackagesPath = GetPackagesPath(project, settings);
restoreMetadata.ProjectName = projectName;
restoreMetadata.ProjectPath = project.FullPath;
restoreMetadata.ProjectStyle = projectStyle;
restoreMetadata.ProjectUniqueName = project.FullPath;
restoreMetadata.ProjectWideWarningProperties = WarningProperties.GetWarningProperties(project.GetProperty("TreatWarningsAsErrors"), project.GetProperty("WarningsAsErrors"), project.GetProperty("NoWarn"));
restoreMetadata.RestoreLockProperties = new RestoreLockProperties(project.GetProperty("RestorePackagesWithLockFile"), project.GetProperty("NuGetLockFilePath"), project.IsPropertyTrue("RestoreLockedMode"));
restoreMetadata.Sources = GetSources(project, innerNodes, settings);
restoreMetadata.TargetFrameworks = GetProjectRestoreMetadataFrameworkInfos(targetFrameworkInfos, projectsByTargetFramework);
return (restoreMetadata, targetFrameworkInfos);
}
/// <summary>
/// Recursively loads and evaluates MSBuild projects.
/// </summary>
/// <param name="entryProjects">An <see cref="IEnumerable{ProjectGraphEntryPoint}" /> containing the entry projects to load.</param>
/// <returns>An <see cref="ICollection{ProjectWithInnerNodes}" /> object containing projects and their inner nodes if they are targeting multiple frameworks.</returns>
private ICollection<ProjectWithInnerNodes> LoadProjects(IEnumerable<ProjectGraphEntryPoint> entryProjects)
{
var loggers = new List<Microsoft.Build.Framework.ILogger>
{
LoggingQueue
};
// Get user specified parameters for a binary logger
string binlogParameters = Environment.GetEnvironmentVariable("RESTORE_TASK_BINLOG_PARAMETERS");
// Attach the binary logger if Debug or binlog parameters were specified
if (Debug || !string.IsNullOrWhiteSpace(binlogParameters))
{
loggers.Add(new BinaryLogger
{
// Default the binlog parameters if only the debug option was specified
Parameters = binlogParameters ?? "LogFile=nuget.binlog"
});
}
var projects = new ConcurrentDictionary<string, ProjectWithInnerNodes>(StringComparer.OrdinalIgnoreCase);
var projectCollection = new ProjectCollection(
globalProperties: null,
// Attach a logger for evaluation only if the Debug option is set
loggers: loggers,
remoteLoggers: null,
toolsetDefinitionLocations: ToolsetDefinitionLocations.Default,
// Having more than 1 node spins up multiple msbuild.exe instances to run builds in parallel
// However, these targets complete so quickly that the added overhead makes it take longer
maxNodeCount: 1,
onlyLogCriticalEvents: false,
// Loading projects as readonly makes parsing a little faster since comments and whitespace can be ignored
loadProjectsReadOnly: true);
var failedBuildSubmissions = new ConcurrentBag<BuildSubmission>();
try
{
var sw = Stopwatch.StartNew();
var evaluationContext = EvaluationContext.Create(EvaluationContext.SharingPolicy.Shared);
ProjectGraph projectGraph;
int buildCount = 0;
var buildParameters = new BuildParameters(projectCollection)
{
// Use the same loggers as the project collection
Loggers = projectCollection.Loggers,
LogTaskInputs = Debug
};
// BeginBuild starts a queue which accepts build requests and applies the build parameters to all of them
BuildManager.DefaultBuildManager.BeginBuild(buildParameters);
try
{
// Create a ProjectGraph object and pass a factory method which creates a ProjectInstance
projectGraph = new ProjectGraph(entryProjects, projectCollection, (path, properties, collection) =>
{
var projectOptions = new ProjectOptions
{
EvaluationContext = evaluationContext,
GlobalProperties = properties,
// Ignore bad imports to maximize the chances of being able to load the project and restore
LoadSettings = ProjectLoadSettings.IgnoreEmptyImports | ProjectLoadSettings.IgnoreInvalidImports | ProjectLoadSettings.IgnoreMissingImports | ProjectLoadSettings.DoNotEvaluateElementsWithFalseCondition,
ProjectCollection = collection
};
// Create a Project object which does the evaluation
var project = Project.FromFile(path, projectOptions);
// Create a ProjectInstance object which is what this factory needs to return
var projectInstance = project.CreateProjectInstance(ProjectInstanceSettings.None, evaluationContext);
if (!projectInstance.Targets.ContainsKey("_IsProjectRestoreSupported") || properties.TryGetValue("TargetFramework", out var targetFramework) && string.IsNullOrWhiteSpace(targetFramework))
{
// In rare cases, users can set an empty TargetFramework value in a project-to-project reference. Static Graph will respect that
// but NuGet does not need to do anything with that instance of the project since the actual project is still loaded correctly
// with its actual TargetFramework.
return projectInstance;
}
// If the project supports restore, queue up a build of the 3 targets needed for restore
BuildManager.DefaultBuildManager
.PendBuildRequest(
new BuildRequestData(
projectInstance,
TargetsToBuild,
hostServices: null,
// Suppresses an error that a target does not exist because it may or may not contain the targets that we're running
BuildRequestDataFlags.SkipNonexistentTargets))
.ExecuteAsync(
callback: buildSubmission =>
{
// If the build failed, add its result to the list to be processed later
if (buildSubmission.BuildResult.OverallResult == BuildResultCode.Failure)
{
failedBuildSubmissions.Add(buildSubmission);
}
},
context: null);
Interlocked.Increment(ref buildCount);
// Add the project instance to the list, if its an inner node for a multi-targeting project it will be added to the inner collection
projects.AddOrUpdate(
path,
key => new ProjectWithInnerNodes(targetFramework, new MSBuildProjectInstance(projectInstance)),
(_, item) => item.Add(targetFramework, new MSBuildProjectInstance(projectInstance)));
return projectInstance;
});
}
finally
{
// EndBuild blocks until all builds are complete
BuildManager.DefaultBuildManager.EndBuild();
}
sw.Stop();
MSBuildLogger.LogInformation(string.Format(CultureInfo.CurrentCulture, Strings.ProjectEvaluationSummary, projectGraph.ProjectNodes.Count, sw.ElapsedMilliseconds, buildCount, failedBuildSubmissions.Count));
if (failedBuildSubmissions.Any())
{
// Return null if any builds failed, they will have logged errors
return null;
}
}
catch (Exception e)
{
LoggingQueue.TaskLoggingHelper.LogErrorFromException(e, showStackTrace: true);
return null;
}
finally
{
projectCollection.Dispose();
}
// Just return the projects not the whole dictionary as it was just used to group the projects together
return projects.Values;
}
/// <summary>
/// It evaluates the project and returns true if the project has CentralPackageVersionManagement enabled.
/// </summary>
/// <param name="project">The <see cref="IMSBuildProject"/> for which the CentralPackageVersionManagement will be evaluated.</param>
/// <param name="projectStyle">The <see cref="ProjectStyle?"/>. Null is the project did not have a defined ProjectRestoreStyle property.</param>
/// <returns>True if the project has CentralPackageVersionManagement enabled and the project is PackageReference or the projectStyle is null.</returns>
internal static bool IsCentralVersionsManagementEnabled(IMSBuildProject project, ProjectStyle? projectStyle)
{
if (!projectStyle.HasValue || (projectStyle.Value == ProjectStyle.PackageReference))
{
return StringComparer.OrdinalIgnoreCase.Equals(project.GetProperty("_CentralPackageVersionsEnabled"), bool.TrueString);
}
return false;
}
/// <summary>
/// Returns the list of distinct items with the <paramref name="itemName"/> name.
/// Two items are equal if they have the same <see cref="IMSBuildItem.Identity"/>.
/// </summary>
/// <param name="project">The project.</param>
/// <param name="itemName">The item name.</param>
/// <returns>Returns the list of items with the <paramref name="itemName"/>. If the item does not exist it will return an empty list.</returns>
private static IEnumerable<IMSBuildItem> GetDistinctItemsOrEmpty(IMSBuildProject project, string itemName)
{
return project.GetItems(itemName)?.Distinct(ProjectItemInstanceEvaluatedIncludeComparer.Instance) ?? Enumerable.Empty<IMSBuildItem>();
}
}
}
| 55.292731 | 283 | 0.636974 | [
"Apache-2.0"
] | ConnectionMaster/NuGet.Client | src/NuGet.Core/NuGet.Build.Tasks.Console/MSBuildStaticGraphRestore.cs | 56,290 | C# |
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
namespace forCrowd.Backbone.BusinessObjects.Entities
{
public class ElementCell : BaseEntity
{
public ElementCell()
{
UserElementCellSet = new HashSet<UserElementCell>();
}
public int Id { get; set; }
[Index("UX_ElementCell_ElementFieldId_ElementItemId", 1, IsUnique = true)]
public int ElementFieldId { get; set; }
[Index("UX_ElementCell_ElementFieldId_ElementItemId", 2, IsUnique = true)]
public int ElementItemId { get; set; }
public string StringValue { get => stringValue; set => stringValue = value?.Trim(); }
public decimal DecimalValueTotal { get; set; }
public int DecimalValueCount { get; set; }
/// <summary>
/// In case this cell's field type is Element, this is the selected item for this cell.
/// Other values are stored on UserElementCell, but since this one has FK, it's directly set on ElementCell.
/// </summary>
public int? SelectedElementItemId { get; set; }
public ElementItem ElementItem { get; set; }
public ElementField ElementField { get; set; }
public ElementItem SelectedElementItem { get; set; }
public ICollection<UserElementCell> UserElementCellSet { get; set; }
public UserElementCell UserElementCell => UserElementCellSet.SingleOrDefault();
string stringValue;
public void SetValue(ElementItem value)
{
SetValueHelper(ElementFieldDataType.Element);
SelectedElementItem = value;
}
public ElementCell SetValue(string value)
{
SetValueHelper(ElementFieldDataType.String);
StringValue = value;
return this;
}
private void SetValueHelper(ElementFieldDataType valueType)
{
// Validations
// a. Field and value types have to match
var fieldType = (ElementFieldDataType)ElementField.DataType;
if (fieldType != valueType)
{
throw new System.InvalidOperationException(
$"Invalid value, field and value types don't match - Field type: {fieldType}, Value type: {valueType}");
}
// Clear, if FixedValue
if (ElementField.UseFixedValue)
ClearFixedValues();
}
private void ClearFixedValues()
{
//StringValue = null;
//DecimalValue = null;
// TODO Do we need to set both?
SelectedElementItemId = null;
SelectedElementItem = null;
}
}
}
| 33.777778 | 124 | 0.612573 | [
"MIT"
] | Augustpi/Backbone | BusinessObjects/Entities/ElementCell.cs | 2,736 | C# |
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using UnityEngine.SceneManagement;
namespace VketTools
{
/// <summary>
/// G.Component規定
/// 07.AnimatorがVRC_PickupおよびVRC_ObjectSyncと併用されていないこと、使用Animationで「../」が使用されていないかとを検証。
/// </summary>
public class AnimatorRule : BaseRule
{
//ルール名
public new string ruleName = "G07 Animator Rule";
public override string RuleName
{
get
{
return ruleName;
}
}
public AnimatorRule(Options _options) : base(_options)
{
}
//検証メソッド
public override Result Validate()
{
//初期化
base.Validate();
//検証ロジック
GameObject[] boothObjects = Utils.GetInstance().FindAllObjectsInBooth();
bool findFlg = false;
bool dirtFlg = false;
if (boothObjects != null)
{
foreach (GameObject obj in boothObjects)
{
//AnimationClipの「../」使用検証
AnimationClip[] clips = AnimationUtility.GetAnimationClips(obj);
if (clips.Length > 0)
{
if (findFlg == false)
{
findFlg = true;
AddResultLog("ブース内のAnimator,Animation:");
}
AddResultLog(string.Format(" {0}", obj.name));
foreach (var clip in clips)
{
foreach (var binding in AnimationUtility.GetCurveBindings(clip))
{
if (binding.path.StartsWith("../"))
{
dirtFlg = true;
AddResultLog(" Animationのパスに「../」は使用できません。");
}
}
}
}
Animator[] animators = obj.GetComponents<UnityEngine.Animator>();
if (animators.Length > 0)
{
//併用コンポーネントの検証
Component[] cmps = obj.GetComponents(typeof(MonoBehaviour));
foreach (Component cmp in cmps)
{
if (cmp != null && cmp.GetType().FullName == "VRCSDK2.VRC_Pickup")
{
dirtFlg = true;
AddResultLog(" AnimatorとVRC_Pickupは同一オブジェクトで併用できません。");
}
if (cmp != null && cmp.GetType().FullName == "VRCSDK2.VRC_ObjectSync")
{
dirtFlg = true;
AddResultLog(" AnimatorとVRC_ObjectSyncpは同一オブジェクトで併用できません。");
}
}
}
}
}
//検証結果を設定して返す(正常:Result.SUCESS 異常:Result.FAIL)
return SetResult(!dirtFlg ? Result.SUCCESS : Result.FAIL);
}
}
}
| 35.358696 | 98 | 0.413157 | [
"MIT"
] | Kozu-vr/VketBoothValidator | VketBoothValidator/Assets/VketBoothValidator/Editor/Rules/G_ComponentLimitation/G07_AnimatorRule.cs | 3,559 | C# |
using System;
using CryptoExchange.Net.Converters;
using Newtonsoft.Json;
namespace Kucoin.Net.Objects.Futures.Socket
{
/// <summary>
/// Index price update
/// </summary>
public class KucoinStreamIndicatorPrice
{
/// <summary>
/// Symbol
/// </summary>
public string Symbol { get; set; } = string.Empty;
/// <summary>
/// Granularity
/// </summary>
public int Granularity { get; set; }
/// <summary>
/// Timestamp
/// </summary>
[JsonConverter(typeof(TimestampConverter))]
public DateTime Timestamp { get; set; }
/// <summary>
/// Value
/// </summary>
public decimal Value { get; set; }
}
}
| 24.322581 | 58 | 0.537135 | [
"MIT"
] | JGronholz/Kucoin.Net | Kucoin.Net/Objects/Futures/Socket/KucoinStreamIndicatorPrice.cs | 756 | C# |
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.Management.Internal.Network.Version2017_10_01.Models
{
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// A common class for general resource information
/// </summary>
[Rest.Serialization.JsonTransformation]
public partial class VirtualNetworkGatewayConnection : Resource
{
/// <summary>
/// Initializes a new instance of the VirtualNetworkGatewayConnection
/// class.
/// </summary>
public VirtualNetworkGatewayConnection()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the VirtualNetworkGatewayConnection
/// class.
/// </summary>
/// <param name="virtualNetworkGateway1">The reference to virtual
/// network gateway resource.</param>
/// <param name="connectionType">Gateway connection type. Possible
/// values are: 'Ipsec','Vnet2Vnet','ExpressRoute', and 'VPNClient.
/// Possible values include: 'IPsec', 'Vnet2Vnet', 'ExpressRoute',
/// 'VPNClient'</param>
/// <param name="id">Resource ID.</param>
/// <param name="name">Resource name.</param>
/// <param name="type">Resource type.</param>
/// <param name="location">Resource location.</param>
/// <param name="tags">Resource tags.</param>
/// <param name="authorizationKey">The authorizationKey.</param>
/// <param name="virtualNetworkGateway2">The reference to virtual
/// network gateway resource.</param>
/// <param name="localNetworkGateway2">The reference to local network
/// gateway resource.</param>
/// <param name="routingWeight">The routing weight.</param>
/// <param name="sharedKey">The IPSec shared key.</param>
/// <param name="connectionStatus">Virtual network Gateway connection
/// status. Possible values are 'Unknown', 'Connecting', 'Connected'
/// and 'NotConnected'. Possible values include: 'Unknown',
/// 'Connecting', 'Connected', 'NotConnected'</param>
/// <param name="tunnelConnectionStatus">Collection of all tunnels'
/// connection health status.</param>
/// <param name="egressBytesTransferred">The egress bytes transferred
/// in this connection.</param>
/// <param name="ingressBytesTransferred">The ingress bytes transferred
/// in this connection.</param>
/// <param name="peer">The reference to peerings resource.</param>
/// <param name="enableBgp">EnableBgp flag</param>
/// <param name="usePolicyBasedTrafficSelectors">Enable policy-based
/// traffic selectors.</param>
/// <param name="ipsecPolicies">The IPSec Policies to be considered by
/// this connection.</param>
/// <param name="resourceGuid">The resource GUID property of the
/// VirtualNetworkGatewayConnection resource.</param>
/// <param name="provisioningState">The provisioning state of the
/// VirtualNetworkGatewayConnection resource. Possible values are:
/// 'Updating', 'Deleting', and 'Failed'.</param>
/// <param name="etag">Gets a unique read-only string that changes
/// whenever the resource is updated.</param>
public VirtualNetworkGatewayConnection(VirtualNetworkGateway virtualNetworkGateway1, string connectionType, string id = default(string), string name = default(string), string type = default(string), string location = default(string), IDictionary<string, string> tags = default(IDictionary<string, string>), string authorizationKey = default(string), VirtualNetworkGateway virtualNetworkGateway2 = default(VirtualNetworkGateway), LocalNetworkGateway localNetworkGateway2 = default(LocalNetworkGateway), int? routingWeight = default(int?), string sharedKey = default(string), string connectionStatus = default(string), IList<TunnelConnectionHealth> tunnelConnectionStatus = default(IList<TunnelConnectionHealth>), long? egressBytesTransferred = default(long?), long? ingressBytesTransferred = default(long?), SubResource peer = default(SubResource), bool? enableBgp = default(bool?), bool? usePolicyBasedTrafficSelectors = default(bool?), IList<IpsecPolicy> ipsecPolicies = default(IList<IpsecPolicy>), string resourceGuid = default(string), string provisioningState = default(string), string etag = default(string))
: base(id, name, type, location, tags)
{
AuthorizationKey = authorizationKey;
VirtualNetworkGateway1 = virtualNetworkGateway1;
VirtualNetworkGateway2 = virtualNetworkGateway2;
LocalNetworkGateway2 = localNetworkGateway2;
ConnectionType = connectionType;
RoutingWeight = routingWeight;
SharedKey = sharedKey;
ConnectionStatus = connectionStatus;
TunnelConnectionStatus = tunnelConnectionStatus;
EgressBytesTransferred = egressBytesTransferred;
IngressBytesTransferred = ingressBytesTransferred;
Peer = peer;
EnableBgp = enableBgp;
UsePolicyBasedTrafficSelectors = usePolicyBasedTrafficSelectors;
IpsecPolicies = ipsecPolicies;
ResourceGuid = resourceGuid;
ProvisioningState = provisioningState;
Etag = etag;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets the authorizationKey.
/// </summary>
[JsonProperty(PropertyName = "properties.authorizationKey")]
public string AuthorizationKey { get; set; }
/// <summary>
/// Gets or sets the reference to virtual network gateway resource.
/// </summary>
[JsonProperty(PropertyName = "properties.virtualNetworkGateway1")]
public VirtualNetworkGateway VirtualNetworkGateway1 { get; set; }
/// <summary>
/// Gets or sets the reference to virtual network gateway resource.
/// </summary>
[JsonProperty(PropertyName = "properties.virtualNetworkGateway2")]
public VirtualNetworkGateway VirtualNetworkGateway2 { get; set; }
/// <summary>
/// Gets or sets the reference to local network gateway resource.
/// </summary>
[JsonProperty(PropertyName = "properties.localNetworkGateway2")]
public LocalNetworkGateway LocalNetworkGateway2 { get; set; }
/// <summary>
/// Gets or sets gateway connection type. Possible values are:
/// 'Ipsec','Vnet2Vnet','ExpressRoute', and 'VPNClient. Possible values
/// include: 'IPsec', 'Vnet2Vnet', 'ExpressRoute', 'VPNClient'
/// </summary>
[JsonProperty(PropertyName = "properties.connectionType")]
public string ConnectionType { get; set; }
/// <summary>
/// Gets or sets the routing weight.
/// </summary>
[JsonProperty(PropertyName = "properties.routingWeight")]
public int? RoutingWeight { get; set; }
/// <summary>
/// Gets or sets the IPSec shared key.
/// </summary>
[JsonProperty(PropertyName = "properties.sharedKey")]
public string SharedKey { get; set; }
/// <summary>
/// Gets virtual network Gateway connection status. Possible values are
/// 'Unknown', 'Connecting', 'Connected' and 'NotConnected'. Possible
/// values include: 'Unknown', 'Connecting', 'Connected',
/// 'NotConnected'
/// </summary>
[JsonProperty(PropertyName = "properties.connectionStatus")]
public string ConnectionStatus { get; private set; }
/// <summary>
/// Gets collection of all tunnels' connection health status.
/// </summary>
[JsonProperty(PropertyName = "properties.tunnelConnectionStatus")]
public IList<TunnelConnectionHealth> TunnelConnectionStatus { get; private set; }
/// <summary>
/// Gets the egress bytes transferred in this connection.
/// </summary>
[JsonProperty(PropertyName = "properties.egressBytesTransferred")]
public long? EgressBytesTransferred { get; private set; }
/// <summary>
/// Gets the ingress bytes transferred in this connection.
/// </summary>
[JsonProperty(PropertyName = "properties.ingressBytesTransferred")]
public long? IngressBytesTransferred { get; private set; }
/// <summary>
/// Gets or sets the reference to peerings resource.
/// </summary>
[JsonProperty(PropertyName = "properties.peer")]
public SubResource Peer { get; set; }
/// <summary>
/// Gets or sets enableBgp flag
/// </summary>
[JsonProperty(PropertyName = "properties.enableBgp")]
public bool? EnableBgp { get; set; }
/// <summary>
/// Gets or sets enable policy-based traffic selectors.
/// </summary>
[JsonProperty(PropertyName = "properties.usePolicyBasedTrafficSelectors")]
public bool? UsePolicyBasedTrafficSelectors { get; set; }
/// <summary>
/// Gets or sets the IPSec Policies to be considered by this
/// connection.
/// </summary>
[JsonProperty(PropertyName = "properties.ipsecPolicies")]
public IList<IpsecPolicy> IpsecPolicies { get; set; }
/// <summary>
/// Gets or sets the resource GUID property of the
/// VirtualNetworkGatewayConnection resource.
/// </summary>
[JsonProperty(PropertyName = "properties.resourceGuid")]
public string ResourceGuid { get; set; }
/// <summary>
/// Gets the provisioning state of the VirtualNetworkGatewayConnection
/// resource. Possible values are: 'Updating', 'Deleting', and
/// 'Failed'.
/// </summary>
[JsonProperty(PropertyName = "properties.provisioningState")]
public string ProvisioningState { get; private set; }
/// <summary>
/// Gets a unique read-only string that changes whenever the resource
/// is updated.
/// </summary>
[JsonProperty(PropertyName = "etag")]
public string Etag { get; set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="ValidationException">
/// Thrown if validation fails
/// </exception>
public virtual void Validate()
{
if (VirtualNetworkGateway1 == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "VirtualNetworkGateway1");
}
if (ConnectionType == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "ConnectionType");
}
if (IpsecPolicies != null)
{
foreach (var element in IpsecPolicies)
{
if (element != null)
{
element.Validate();
}
}
}
}
}
}
| 46.960938 | 1,123 | 0.618034 | [
"MIT"
] | Azure/azure-powershell-common | src/Network/Version2017_10_01/Models/VirtualNetworkGatewayConnection.cs | 12,022 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace System.Threading
{
internal static class CancellationTokenExtensions
{
internal static CancellationTokenRegistration UnsafeRegister(this CancellationToken cancellationToken, Action<object> callback, object state)
{
return cancellationToken.Register(callback, state);
}
}
}
| 26.5 | 149 | 0.742925 | [
"MIT"
] | 2E0PGS/corefx | src/System.IO.Pipelines/src/System/IO/Pipelines/CancellationTokenExtensions.netstandard.cs | 426 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations.Schema;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
namespace YiSha.Data.EF
{
/// <summary>
/// 主键约定,把属性Id当做数据库主键
/// </summary>
public class PrimaryKeyConvention
{
public static void SetPrimaryKey(ModelBuilder modelBuilder, string entityName)
{
modelBuilder.Entity(entityName).HasKey("Id");
}
}
/// <summary>
/// 列名约定,比如属性ParentId,映射到数据库字段parent_id
/// </summary>
[Obsolete]
public class ColumnConvention
{
public static void SetColumnName(ModelBuilder modelBuilder, string entityName, string propertyName)
{
StringBuilder sbField = new StringBuilder();
char[] charArr = propertyName.ToCharArray();
int iCapital = 0; // 把属性第一个开始的大写字母转成小写,直到遇到了第1个小写字母,因为数据库里面是小写的
while (iCapital < charArr.Length)
{
if (charArr[iCapital] >= 'A' && charArr[iCapital] <= 'Z')
{
charArr[iCapital] = (char)(charArr[iCapital] + 32);
}
else
{
break;
}
iCapital++;
}
for (int i = 0; i < charArr.Length; i++)
{
if (charArr[i] >= 'A' && charArr[i] <= 'Z')
{
charArr[i] = (char)(charArr[i] + 32);
sbField.Append("_" + charArr[i]);
}
else
{
sbField.Append(charArr[i]);
}
}
modelBuilder.Entity(entityName).Property(propertyName).HasColumnName(sbField.ToString());
}
}
}
| 30.453125 | 108 | 0.509492 | [
"MIT"
] | lizhaoiot/pomsbs | YiSha.Data/YiSha.Data.EF/MapConventions.cs | 2,099 | C# |
using Maple.Core.Infrastructure;
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Maple.Web.Framework.Infrastructure.Extensions;
namespace Maple.Web.Framework.Infrastructure
{
/// <summary>
/// 用于在应用程序启动时执行MVC相关配置
/// </summary>
public class MapleMvcStartup : IMapleStartup
{
public int Order => 1000;
public void Configure(IApplicationBuilder application)
{
//???
////add MiniProfiler
//application.UseMiniProfiler();
//MVC 路由配置
application.UseMapleMvc();
}
public void ConfigureServices(IServiceCollection services, IConfigurationRoot configuration)
{
//???
////add MiniProfiler services
//services.AddMiniProfiler();
//为应用程序添加和配置MVC
services.AddMapleMvc();
}
}
}
| 26.475 | 101 | 0.614731 | [
"BSD-3-Clause"
] | fengqinhua/Maple | src/Maple.Web.Framework/Infrastructure/MapleMvcStartup.cs | 1,121 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LoadAddYes : MonoBehaviour
{
public void ClickedYes()
{
if (LoadGameManager.started == true)
{
LoadGameManager.addYesButton.SetActive(false);
LoadGameManager.addNoButton.SetActive(false);
LoadGameManager.resetButton.SetActive(true);
LoadGameManager.startOverButton.SetActive(true);
LoadGameManager.parent.yesNode = new PeopleNode(LoadGameManager.newPerson);
LoadGameManager.parent.noNode = LoadGameManager.current;
LoadGameManager.current = LoadGameManager.parent;
LoadGameManager.started = false;
}
else
{
LoadGameManager.addYesButton.SetActive(false);
LoadGameManager.addNoButton.SetActive(false);
LoadGameManager.resetButton.SetActive(true);
LoadGameManager.startOverButton.SetActive(true);
if (LoadGameManager.prevMoveRight == true)
{
LoadGameManager.parent.noNode = LoadGameManager.savedNode;
LoadGameManager.parent.noNode.yesNode = new PeopleNode(LoadGameManager.newPerson);
LoadGameManager.parent.noNode.noNode = LoadGameManager.current;
}
else if (LoadGameManager.prevMoveLeft == true)
{
LoadGameManager.parent.yesNode = LoadGameManager.savedNode;
LoadGameManager.parent.yesNode.yesNode = new PeopleNode(LoadGameManager.newPerson);
LoadGameManager.parent.yesNode.noNode = LoadGameManager.current;
}
}
}
}
| 40.95122 | 99 | 0.649792 | [
"Apache-2.0"
] | pab15/Tree-Milestone | Guessing-Game/Assets/Scripts/LoadAddYes.cs | 1,681 | C# |
namespace DFrame.Kubernetes.Models
{
public class V1TopologySpreadConstraint
{
public V1LabelSelector LabelSelector { get; set; }
public int MaxSkew { get; set; }
public string TopologyKey { get; set; }
public string WhenUnsatisfiable { get; set; }
}
}
| 27.090909 | 58 | 0.651007 | [
"MIT"
] | Cysharp/DFrame | src/DFrame.Kubernetes/Models/V1TopologySpreadConstraint.cs | 300 | C# |
using BGB.Gerencial.Domain.Extensions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
namespace BGB.Gerencial.Domain.Tests.Extensions
{
[TestClass]
public class LastDayInMonthTests
{
[TestMethod]
[DataRow("2020-01-01", "2020-01-31")]
[DataRow("2020-02-05", "2020-02-29")]
[DataRow("2019-02-05", "2019-02-28")]
[DataRow("2020-03-29", "2020-03-31")]
public void EscreverTaxaContratual(string data, string ultimoDiaMes)
{
DateTime dataBusca = DateTime.Parse(data).LastDayInMonth();
DateTime dataEsperada = DateTime.Parse(ultimoDiaMes).LastDayInMonth();
Assert.AreEqual(dataBusca, dataEsperada);
}
}
}
| 29.48 | 82 | 0.644505 | [
"MIT"
] | nelson1987/ContractualManager | BGB.Gerencial.Domain.Tests/Extensions/LastDayInMonthTests.cs | 739 | 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("03. Non-Digit Count")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("03. Non-Digit Count")]
[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("7249c670-1d67-438c-be0c-07dc1d54b1ca")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38 | 84 | 0.744666 | [
"MIT"
] | NikolaySpasov/Softuni | C# Advanced/06. Lab - Regular Expresions/03. Non-Digit Count/Properties/AssemblyInfo.cs | 1,409 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.ResourceManager;
using Azure.ResourceManager.Core;
namespace Azure.ResourceManager.Resources
{
/// <summary> A class representing collection of TenantPolicySetDefinition and their operations over its parent. </summary>
public partial class TenantPolicySetDefinitionCollection : ArmCollection, IEnumerable<TenantPolicySetDefinition>, IAsyncEnumerable<TenantPolicySetDefinition>
{
private readonly ClientDiagnostics _tenantPolicySetDefinitionPolicySetDefinitionsClientDiagnostics;
private readonly PolicySetDefinitionsRestOperations _tenantPolicySetDefinitionPolicySetDefinitionsRestClient;
/// <summary> Initializes a new instance of the <see cref="TenantPolicySetDefinitionCollection"/> class for mocking. </summary>
protected TenantPolicySetDefinitionCollection()
{
}
/// <summary> Initializes a new instance of the <see cref="TenantPolicySetDefinitionCollection"/> class. </summary>
/// <param name="client"> The client parameters to use in these operations. </param>
/// <param name="id"> The identifier of the parent resource that is the target of operations. </param>
internal TenantPolicySetDefinitionCollection(ArmClient client, ResourceIdentifier id) : base(client, id)
{
_tenantPolicySetDefinitionPolicySetDefinitionsClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Resources", TenantPolicySetDefinition.ResourceType.Namespace, DiagnosticOptions);
TryGetApiVersion(TenantPolicySetDefinition.ResourceType, out string tenantPolicySetDefinitionPolicySetDefinitionsApiVersion);
_tenantPolicySetDefinitionPolicySetDefinitionsRestClient = new PolicySetDefinitionsRestOperations(Pipeline, DiagnosticOptions.ApplicationId, BaseUri, tenantPolicySetDefinitionPolicySetDefinitionsApiVersion);
#if DEBUG
ValidateResourceId(Id);
#endif
}
internal static void ValidateResourceId(ResourceIdentifier id)
{
if (id.ResourceType != Tenant.ResourceType)
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, Tenant.ResourceType), nameof(id));
}
/// <summary>
/// This operation retrieves the built-in policy set definition with the given name.
/// Request Path: /providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName}
/// Operation Id: PolicySetDefinitions_GetBuiltIn
/// </summary>
/// <param name="policySetDefinitionName"> The name of the policy set definition to get. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="policySetDefinitionName"/> is an empty string, and was expected to be non-empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="policySetDefinitionName"/> is null. </exception>
public virtual async Task<Response<TenantPolicySetDefinition>> GetAsync(string policySetDefinitionName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName));
using var scope = _tenantPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("TenantPolicySetDefinitionCollection.Get");
scope.Start();
try
{
var response = await _tenantPolicySetDefinitionPolicySetDefinitionsRestClient.GetBuiltInAsync(policySetDefinitionName, cancellationToken).ConfigureAwait(false);
if (response.Value == null)
throw new RequestFailedException(response.GetRawResponse());
return Response.FromValue(new TenantPolicySetDefinition(Client, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// This operation retrieves the built-in policy set definition with the given name.
/// Request Path: /providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName}
/// Operation Id: PolicySetDefinitions_GetBuiltIn
/// </summary>
/// <param name="policySetDefinitionName"> The name of the policy set definition to get. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="policySetDefinitionName"/> is an empty string, and was expected to be non-empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="policySetDefinitionName"/> is null. </exception>
public virtual Response<TenantPolicySetDefinition> Get(string policySetDefinitionName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName));
using var scope = _tenantPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("TenantPolicySetDefinitionCollection.Get");
scope.Start();
try
{
var response = _tenantPolicySetDefinitionPolicySetDefinitionsRestClient.GetBuiltIn(policySetDefinitionName, cancellationToken);
if (response.Value == null)
throw new RequestFailedException(response.GetRawResponse());
return Response.FromValue(new TenantPolicySetDefinition(Client, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// This operation retrieves a list of all the built-in policy set definitions that match the optional given $filter. If $filter='category -eq {value}' is provided, the returned list only includes all built-in policy set definitions whose category match the {value}.
/// Request Path: /providers/Microsoft.Authorization/policySetDefinitions
/// Operation Id: PolicySetDefinitions_ListBuiltIn
/// </summary>
/// <param name="filter"> The filter to apply on the operation. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list only includes all policy set definitions that at the given scope. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy set definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy set definitions whose category match the {value}. </param>
/// <param name="top"> Maximum number of records to return. When the $top filter is not provided, it will return 500 records. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <returns> An async collection of <see cref="TenantPolicySetDefinition" /> that may take multiple service requests to iterate over. </returns>
public virtual AsyncPageable<TenantPolicySetDefinition> GetAllAsync(string filter = null, int? top = null, CancellationToken cancellationToken = default)
{
async Task<Page<TenantPolicySetDefinition>> FirstPageFunc(int? pageSizeHint)
{
using var scope = _tenantPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("TenantPolicySetDefinitionCollection.GetAll");
scope.Start();
try
{
var response = await _tenantPolicySetDefinitionPolicySetDefinitionsRestClient.ListBuiltInAsync(filter, top, cancellationToken: cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value.Select(value => new TenantPolicySetDefinition(Client, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
async Task<Page<TenantPolicySetDefinition>> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = _tenantPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("TenantPolicySetDefinitionCollection.GetAll");
scope.Start();
try
{
var response = await _tenantPolicySetDefinitionPolicySetDefinitionsRestClient.ListBuiltInNextPageAsync(nextLink, filter, top, cancellationToken: cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value.Select(value => new TenantPolicySetDefinition(Client, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, NextPageFunc);
}
/// <summary>
/// This operation retrieves a list of all the built-in policy set definitions that match the optional given $filter. If $filter='category -eq {value}' is provided, the returned list only includes all built-in policy set definitions whose category match the {value}.
/// Request Path: /providers/Microsoft.Authorization/policySetDefinitions
/// Operation Id: PolicySetDefinitions_ListBuiltIn
/// </summary>
/// <param name="filter"> The filter to apply on the operation. Valid values for $filter are: 'atExactScope()', 'policyType -eq {value}' or 'category eq '{value}''. If $filter is not provided, no filtering is performed. If $filter=atExactScope() is provided, the returned list only includes all policy set definitions that at the given scope. If $filter='policyType -eq {value}' is provided, the returned list only includes all policy set definitions whose type match the {value}. Possible policyType values are NotSpecified, BuiltIn, Custom, and Static. If $filter='category -eq {value}' is provided, the returned list only includes all policy set definitions whose category match the {value}. </param>
/// <param name="top"> Maximum number of records to return. When the $top filter is not provided, it will return 500 records. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <returns> A collection of <see cref="TenantPolicySetDefinition" /> that may take multiple service requests to iterate over. </returns>
public virtual Pageable<TenantPolicySetDefinition> GetAll(string filter = null, int? top = null, CancellationToken cancellationToken = default)
{
Page<TenantPolicySetDefinition> FirstPageFunc(int? pageSizeHint)
{
using var scope = _tenantPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("TenantPolicySetDefinitionCollection.GetAll");
scope.Start();
try
{
var response = _tenantPolicySetDefinitionPolicySetDefinitionsRestClient.ListBuiltIn(filter, top, cancellationToken: cancellationToken);
return Page.FromValues(response.Value.Value.Select(value => new TenantPolicySetDefinition(Client, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
Page<TenantPolicySetDefinition> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = _tenantPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("TenantPolicySetDefinitionCollection.GetAll");
scope.Start();
try
{
var response = _tenantPolicySetDefinitionPolicySetDefinitionsRestClient.ListBuiltInNextPage(nextLink, filter, top, cancellationToken: cancellationToken);
return Page.FromValues(response.Value.Value.Select(value => new TenantPolicySetDefinition(Client, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateEnumerable(FirstPageFunc, NextPageFunc);
}
/// <summary>
/// Checks to see if the resource exists in azure.
/// Request Path: /providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName}
/// Operation Id: PolicySetDefinitions_GetBuiltIn
/// </summary>
/// <param name="policySetDefinitionName"> The name of the policy set definition to get. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="policySetDefinitionName"/> is an empty string, and was expected to be non-empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="policySetDefinitionName"/> is null. </exception>
public virtual async Task<Response<bool>> ExistsAsync(string policySetDefinitionName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName));
using var scope = _tenantPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("TenantPolicySetDefinitionCollection.Exists");
scope.Start();
try
{
var response = await GetIfExistsAsync(policySetDefinitionName, cancellationToken: cancellationToken).ConfigureAwait(false);
return Response.FromValue(response.Value != null, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Checks to see if the resource exists in azure.
/// Request Path: /providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName}
/// Operation Id: PolicySetDefinitions_GetBuiltIn
/// </summary>
/// <param name="policySetDefinitionName"> The name of the policy set definition to get. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="policySetDefinitionName"/> is an empty string, and was expected to be non-empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="policySetDefinitionName"/> is null. </exception>
public virtual Response<bool> Exists(string policySetDefinitionName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName));
using var scope = _tenantPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("TenantPolicySetDefinitionCollection.Exists");
scope.Start();
try
{
var response = GetIfExists(policySetDefinitionName, cancellationToken: cancellationToken);
return Response.FromValue(response.Value != null, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Tries to get details for this resource from the service.
/// Request Path: /providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName}
/// Operation Id: PolicySetDefinitions_GetBuiltIn
/// </summary>
/// <param name="policySetDefinitionName"> The name of the policy set definition to get. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="policySetDefinitionName"/> is an empty string, and was expected to be non-empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="policySetDefinitionName"/> is null. </exception>
public virtual async Task<Response<TenantPolicySetDefinition>> GetIfExistsAsync(string policySetDefinitionName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName));
using var scope = _tenantPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("TenantPolicySetDefinitionCollection.GetIfExists");
scope.Start();
try
{
var response = await _tenantPolicySetDefinitionPolicySetDefinitionsRestClient.GetBuiltInAsync(policySetDefinitionName, cancellationToken: cancellationToken).ConfigureAwait(false);
if (response.Value == null)
return Response.FromValue<TenantPolicySetDefinition>(null, response.GetRawResponse());
return Response.FromValue(new TenantPolicySetDefinition(Client, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Tries to get details for this resource from the service.
/// Request Path: /providers/Microsoft.Authorization/policySetDefinitions/{policySetDefinitionName}
/// Operation Id: PolicySetDefinitions_GetBuiltIn
/// </summary>
/// <param name="policySetDefinitionName"> The name of the policy set definition to get. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="policySetDefinitionName"/> is an empty string, and was expected to be non-empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="policySetDefinitionName"/> is null. </exception>
public virtual Response<TenantPolicySetDefinition> GetIfExists(string policySetDefinitionName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(policySetDefinitionName, nameof(policySetDefinitionName));
using var scope = _tenantPolicySetDefinitionPolicySetDefinitionsClientDiagnostics.CreateScope("TenantPolicySetDefinitionCollection.GetIfExists");
scope.Start();
try
{
var response = _tenantPolicySetDefinitionPolicySetDefinitionsRestClient.GetBuiltIn(policySetDefinitionName, cancellationToken: cancellationToken);
if (response.Value == null)
return Response.FromValue<TenantPolicySetDefinition>(null, response.GetRawResponse());
return Response.FromValue(new TenantPolicySetDefinition(Client, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
IEnumerator<TenantPolicySetDefinition> IEnumerable<TenantPolicySetDefinition>.GetEnumerator()
{
return GetAll().GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetAll().GetEnumerator();
}
IAsyncEnumerator<TenantPolicySetDefinition> IAsyncEnumerable<TenantPolicySetDefinition>.GetAsyncEnumerator(CancellationToken cancellationToken)
{
return GetAllAsync(cancellationToken: cancellationToken).GetAsyncEnumerator(cancellationToken);
}
}
}
| 63.425076 | 771 | 0.682835 | [
"MIT"
] | KurnakovMaksim/azure-sdk-for-net | sdk/resourcemanager/Azure.ResourceManager/src/Resources/Generated/TenantPolicySetDefinitionCollection.cs | 20,740 | C# |
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System.Threading.Tasks;
using CoreLibrary.Ports.In;
namespace Functions
{
public class State
{
private static State _instance;
private Facade facade;
private State()
{
facade = new Facade(new PortCosmosRepository.Repository());
}
public static State instance()
{
if (_instance == null)
{
_instance = new State();
}
return _instance;
}
public static Facade Facade() =>
instance().facade;
}
public static class Http
{
[FunctionName("friends")]
public static async Task<IActionResult> Family(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest req,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
string name = req.Query["name"];
log.LogInformation($"name is '{name}'");
var results = await State.Facade().FindOnLastName(name);
log.LogInformation(results.ToString());
return new OkObjectResult(JsonConvert.SerializeObject(results));
}
}
}
| 24.254237 | 93 | 0.599581 | [
"MIT"
] | graeme-lockley/tutorial-azure-functions-cosmosdb-csharp | src/Functions/Http.cs | 1,431 | C# |
using System;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
namespace BUCommon
{
namespace Models
{
public class Hash
{
public int id {get;set;}
public string type {get;set;}
public string base64 {get;set;}
}
public class ContFile
{
public int id {get;set;}
public long accountID {get;set;}
public string containerID {get;set;}
public string path {get;set;}
public string mimeType {get;set; }
public int? storedHashID {get;set; }
/// <summary>hash for the non-encrypted contents</summary>
public int? localHashID {get;set; }
public DateTime modified {get;set; }
/// <summary>when this file was uploaded to the provider</summary>
public DateTime uploaded {get;set; }
/// <summary>cloud provider ID</summary>
public string fileID {get;set; }
public string serviceInfo {get;set;}
public string enchash {get;set;}
public Hash storedHash {get;set;}
public Hash localHash {get;set;}
}
}
public class CacheDBContext : DbContext
{
public const string Db_File = "b2app.cachedb.db";
public static CacheDBContext Build(string path)
{
var opts = new DbContextOptionsBuilder();
opts.UseSqlite(string.Format("Data Source={0}", System.IO.Path.Combine(path, Db_File)));
var db = new CacheDBContext(opts.Options);
db.Database.EnsureCreated();
return db;
}
public DbSet<Models.ContFile> Files {get;set;}
public DbSet<Models.Hash> Hashes {get;set;}
public CacheDBContext(DbContextOptions opts) : base(opts) { }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{ optionsBuilder.UseSqlite("Data Source=cache.db"); }
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
/*
var ae = modelBuilder.Entity<Models.Account>();
ae.HasKey(x => x.id);
ae.Property(x => x.id)
//.HasColumnType("INTEGER AUTOINCREMENT")
.ValueGeneratedOnAdd();
ae.Property(x => x.name)
.IsRequired();
ae.Property(x => x.accountID).IsRequired();
*/
// freezefile
var ffEntity = modelBuilder.Entity<Models.ContFile>();
ffEntity.HasKey(x => x.id);
ffEntity.Property(x => x.id)
//.HasColumnType("INTEGER PRIMARY KEY AUTOINCREMENT")
.ValueGeneratedOnAdd();
ffEntity.Property(x => x.containerID)
.IsRequired();
ffEntity.Property(x => x.fileID)
.IsRequired();
ffEntity.Property(x => x.uploaded)
.IsRequired();
// hashes
var he = modelBuilder.Entity<Models.Hash>();
he.HasKey(x => x.id);
he.Property(x => x.id)
//.HasColumnType("INTEGER PRIMARY KEY AUTOINCREMENT")
.ValueGeneratedOnAdd();
he.Property(x => x.type)
.IsRequired();
he.Property(x => x.base64)
.IsRequired();
/*
var ce = modelBuilder.Entity<Models.Container>();
ce.HasKey(x => x.id);
ce.Property(x => x.id)
//.HasColumnType("INTEGER PRIMARY KEY AUTOINCREMENT")
.ValueGeneratedOnAdd();
ce.Property(x => x.type)
.IsRequired();
ce.Property(x => x.name)
.IsRequired();
ce.Property(x => x.containerID).IsRequired();
ce.Property(x => x.accountID).IsRequired();
ce.Ignore(x => x.account);
ce.Ignore(x => x.files);
*/
}
}
}
| 28.063492 | 94 | 0.611425 | [
"MIT"
] | cptnalf/b2_autopush | BUCommon/CacheDbContext.cs | 3,536 | C# |
namespace AjTalk.Language
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
public class Method : Block, IMethod
{
private string name;
private IBehavior mthclass;
public Method(string name)
: this(null, name, null)
{
}
public Method(IBehavior cls, string name)
: this(cls, name, null)
{
}
public Method(IBehavior cls, string name, string source)
: base(source)
{
this.name = name;
this.mthclass = cls;
}
public IBehavior Behavior
{
get { return this.mthclass; }
}
public string Name
{
get
{
return this.name;
}
}
public override bool IsMethod { get { return true; } }
public override void CompileGet(string name)
{
if (this.TryCompileGet(name))
{
return;
}
this.CompileByteCode(ByteCode.GetGlobalVariable, this.CompileGlobal(name));
}
public override void CompileSet(string name)
{
if (this.TryCompileSet(name))
return;
this.CompileByteCode(ByteCode.SetGlobalVariable, CompileGlobal(name));
}
// TODO how to implements super, sender
public override object Execute(Machine machine, object[] args)
{
throw new InvalidOperationException("A method needs a self object");
}
public object Execute(Machine machine, IObject self, object[] args)
{
return (new Interpreter(new ExecutionContext(machine, self, this, args))).Execute();
}
public object ExecuteInInterpreter(Interpreter interpreter, IObject self, object[] args)
{
interpreter.PushContext(new ExecutionContext(interpreter.Machine, self, this, args));
return interpreter;
}
public object ExecuteNative(Machine machine, object self, object[] args)
{
return (new Interpreter(new ExecutionContext(machine, self, this, args))).Execute();
}
public object ExecuteNativeInInterpreter(Interpreter interpreter, object self, object[] args)
{
interpreter.PushContext(new ExecutionContext(interpreter.Machine, self, this, args));
return interpreter;
}
public override string GetInstanceVariableName(int n)
{
return ((IClassDescription)this.mthclass).GetInstanceVariableNames().ElementAt(n);
}
public override string GetClassVariableName(int n)
{
return ((IClassDescription)this.mthclass).GetClassVariableNames().ElementAt(n);
}
public override int GetInstanceVariableOffset(string name)
{
var cls = this.mthclass as IClassDescription;
if (cls == null)
return -1;
return cls.GetInstanceVariableOffset(name);
}
internal void SetBehavior(IBehavior behavior)
{
this.mthclass = behavior;
}
protected override bool TryCompileGet(string name)
{
if (base.TryCompileGet(name))
return true;
if (this.mthclass == null)
return false;
IClassDescription cls = this.mthclass as IClassDescription;
if (cls == null)
return false;
int p = cls.GetInstanceVariableOffset(name);
if (p >= 0)
{
CompileByteCode(ByteCode.GetInstanceVariable, (byte)p);
return true;
}
p = cls.GetClassVariableOffset(name);
if (p >= 0)
{
CompileByteCode(ByteCode.GetClassVariable, (byte)p);
return true;
}
return false;
}
protected override bool TryCompileSet(string name)
{
if (base.TryCompileSet(name))
return true;
if (this.mthclass == null)
return false;
IClassDescription cls = this.mthclass as IClassDescription;
if (cls == null)
return false;
int p = cls.GetInstanceVariableOffset(name);
if (p >= 0)
{
this.CompileByteCode(ByteCode.SetInstanceVariable, (byte)p);
return true;
}
p = cls.GetClassVariableOffset(name);
if (p >= 0)
{
this.CompileByteCode(ByteCode.SetClassVariable, (byte)p);
return true;
}
return false;
}
}
}
| 28.022346 | 102 | 0.520335 | [
"MIT"
] | ajlopez/AjTalk | Src/AjTalk/Language/Method.cs | 5,016 | C# |
using System;
using System.Numerics;
using System.Collections.Generic;
using Iril.Types;
using System.Linq;
using System.Globalization;
namespace Iril.IR
{
public abstract class Constant : Value
{
public abstract int Int32Value { get; }
public override int GetInt32Value (Module module) => Int32Value;
}
public abstract class SimpleConstant : Constant
{
public override IEnumerable<GlobalSymbol> ReferencedGlobals => Enumerable.Empty<GlobalSymbol> ();
public override bool IsIdempotent (FunctionDefinition function) => true;
}
public abstract class ComplexConstant : Constant
{
}
public class TypedConstant
{
public readonly LType Type;
public readonly Constant Constant;
public TypedConstant (LType type, Constant constant)
{
Type = type;
Constant = constant ?? throw new ArgumentNullException (nameof (constant));
}
public override string ToString () => $"{Type} {Constant}";
}
public class BooleanConstant : SimpleConstant
{
public static readonly BooleanConstant True = new BooleanConstant (true);
public static readonly BooleanConstant False = new BooleanConstant (false);
public readonly bool IsTrue;
BooleanConstant (bool isTrue)
{
IsTrue = isTrue;
}
public override int Int32Value => IsTrue ? 1 : 0;
public override string ToString () => IsTrue ? "true" : "false";
}
public class BytesConstant : Constant
{
public readonly Symbol Bytes;
public BytesConstant (Symbol bytes)
{
Bytes = bytes ?? throw new ArgumentNullException (nameof (bytes));
}
public override int Int32Value => 0;
public override string ToString () => $"{Bytes}";
public override IEnumerable<GlobalSymbol> ReferencedGlobals => Enumerable.Empty<GlobalSymbol> ();
}
public class IntegerConstant : SimpleConstant
{
public static readonly IntegerConstant Zero = new IntegerConstant (BigInteger.Zero);
public static readonly IntegerConstant One = new IntegerConstant (BigInteger.One);
public static readonly IntegerConstant B1 = new IntegerConstant (BigInteger.One);
public static readonly IntegerConstant B11 = new IntegerConstant (0b11);
public static readonly IntegerConstant B111 = new IntegerConstant (0b111);
public static readonly IntegerConstant B1111 = new IntegerConstant (0b1111);
public static readonly IntegerConstant B11111 = new IntegerConstant (0b11111);
public static readonly IntegerConstant B111111 = new IntegerConstant (0b111111);
public static readonly IntegerConstant B1111111 = new IntegerConstant (0b1111111);
public static readonly IntegerConstant B11111111 = new IntegerConstant (0b11111111);
public readonly BigInteger Value;
public IntegerConstant (BigInteger value)
{
Value = value;
}
public override int Int32Value => (int)Value;
public override string ToString () => Value.ToString ();
public static IntegerConstant MaskBits (int bits)
{
switch (bits) {
case 0:
return Zero;
case 1:
return One;
case 2:
return B11;
case 3:
return B111;
case 4:
return B1111;
case 5:
return B11111;
case 6:
return B111111;
case 7:
return B1111111;
case 8:
return B11111111;
default: { var m = (BigInteger.One << bits) - 1;
return new IntegerConstant (m);
}
}
}
}
public class HexIntegerConstant : SimpleConstant
{
public readonly BigInteger Value;
public HexIntegerConstant (BigInteger value)
{
Value = value;
}
public override int Int32Value => (int)Value;
public override string ToString () => $"0x{Value:X}";
}
public class FloatConstant : SimpleConstant
{
public readonly double Value;
public FloatConstant (double value)
{
Value = value;
}
public override int Int32Value => (int)Math.Round (Value);
public override string ToString () => Value.ToString (System.Globalization.CultureInfo.InvariantCulture);
}
public class NullConstant : SimpleConstant
{
public static readonly NullConstant Null = new NullConstant ();
NullConstant ()
{
}
public override int Int32Value => 0;
public override string ToString () => "null";
}
public class StructureConstant : ComplexConstant
{
public readonly TypedValue[] Elements;
public StructureConstant (IEnumerable<TypedValue> elements)
{
if (elements == null) {
throw new ArgumentNullException (nameof (elements));
}
Elements = elements.ToArray ();
}
public override IEnumerable<LocalSymbol> ReferencedLocals => Elements.SelectMany (x => x.Value.ReferencedLocals);
public override IEnumerable<GlobalSymbol> ReferencedGlobals => Elements.SelectMany (x => x.Value.ReferencedGlobals);
public override int Int32Value => 0;
}
public class UndefinedConstant : SimpleConstant
{
public static UndefinedConstant Undefined = new UndefinedConstant ();
public override string ToString () => "undef";
public override int Int32Value => 0;
}
public class ZeroConstant : SimpleConstant
{
public static ZeroConstant Zero = new ZeroConstant ();
public override string ToString () => "zeroinitializer";
public override int Int32Value => 0;
}
}
| 29.545894 | 124 | 0.606933 | [
"MIT"
] | praeclarum/Iril | Iril/IR/Constants.cs | 6,118 | C# |
using Mindstorms.Core.Enums;
namespace Mindstorms.Core.Commands.Program
{
public abstract class StopBase : Command
{
public StopBase(ProgramSlot programslot)
{
data = DirectCommandNoReply;
data.Add(OpCode.ProgramStop);
data.Add(programslot);
}
}
}
| 21.466667 | 48 | 0.614907 | [
"MIT"
] | Mortens4444/LegoMindstromsEV3 | Mindstorms.Core/Commands/Program/StopBase.cs | 324 | C# |
namespace StorageMester.Tests.Structure
{
using NUnit.Framework;
using StorageMaster.Entities.Products;
using System;
using System.Linq;
using System.Reflection;
public class ProductsTests
{
private Type type;
[SetUp]
public void SetUp()
{
type = typeof(Product);
}
[Test]
public void Constructor_ShouldReturnCorrectCountOfConstructors()
{
var constructors = type.GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
Assert.IsTrue(constructors.Length == 1, "The type has no constructor!");
}
[Test]
public void Constructor_ShouldNotAllowInitialisation()
{
var constructor = type.GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public).First();
Assert.Throws<MemberAccessException>(() => { var instance = (Product)constructor.Invoke(new object[] { 5, 10 }); },
"Constructor should not allow the class to be initialised as it is abstract!");
}
[Test]
public void Field_ShouldHaveFieldsOfTypeDouble()
{
var fields = type.GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
foreach (var field in fields)
{
Assert.That(field.FieldType == typeof(double), "Field is not of expected type!");
}
}
[Test]
public void Field_ShouldReturnCorrectCountOfFields()
{
var fields = type.GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
Assert.AreEqual(2, fields.Length, "Count of fields mismatch!");
}
[Test]
public void Property_ShouldReturnCorrectCountOfProperties()
{
var props = type.GetProperties(BindingFlags.Instance | BindingFlags.Public);
Assert.AreEqual(2, props.Length, "Count of properties mismatch!");
}
[Test]
public void Property_ShouldHaveCorrectNamesOfProperties()
{
var propsNames = type.GetProperties(BindingFlags.Instance | BindingFlags.Public).Select(p => p.Name);
var expected = new string[] { "Price", "Weight" };
CollectionAssert.AreEqual(expected, propsNames, "Names of class properties mismatch!");
}
[Test]
public void Method_PrivateSetters_ShouldReturnCorrectCount()
{
var setters = type.GetMethods(BindingFlags.Instance | BindingFlags.NonPublic).Where(m => m.Name.StartsWith("set"));
Assert.AreEqual(1, setters.Count(), "Private Setters count mismatch!");
}
[Test]
public void Method_PublicGetters_ShouldReturnCorrectCount()
{
var getters = type.GetMethods(BindingFlags.Instance | BindingFlags.Public).Where(m => m.Name.StartsWith("get"));
Assert.AreEqual(2, getters.Count(), "Public Getters count mismatch!");
}
[Test]
public void Consts_AllSpecificProducts_ShouldSetConstsAndPropertyValuesCorrectlyUponInitialisation()
{
var gpu = new Gpu(5);
var hd = new HardDrive(10);
var ram = new Ram(50);
var ssd = new SolidStateDrive(100);
Assert.AreEqual(0.7, gpu.Weight, "GPU weight mismatch!");
Assert.AreEqual(1, hd.Weight, "Hard Drive weight mismatch!");
Assert.AreEqual(0.1, ram.Weight, "RAM weight mismatch!");
Assert.AreEqual(0.2, ssd.Weight, "Solid State Drive weight mismatch!");
Assert.AreEqual(5, gpu.Price, "GPU price mismatch!");
Assert.AreEqual(10, hd.Price, "Hard Drive price mismatch!");
Assert.AreEqual(50, ram.Price, "RAM price mismatch!");
Assert.AreEqual(100, ssd.Price, "Solid State Drive price mismatch!");
}
[Test]
public void Consts_AllSpecificProducts_ShouldThrowExceptionWithNegativePrice()
{
Assert.Throws<InvalidOperationException>(() => { var gpu = new Gpu(-1); });
Assert.Throws<InvalidOperationException>(() => { var ram = new Ram(-1); });
Assert.Throws<InvalidOperationException>(() => { var hd = new SolidStateDrive(-1); });
Assert.Throws<InvalidOperationException>(() => { var ssd = new HardDrive(-1); });
}
}
}
| 38.982301 | 129 | 0.616572 | [
"MIT"
] | kovachevmartin/SoftUni | CSharp-OOP/08-UNIT_TESTING/P04.StorageMaster/StorageMester.Tests.Structure/ProductsTests.cs | 4,407 | C# |
using System.IO;
using System.Threading.Tasks;
using FluentAssertions;
using LeetSharpTool.Models;
using Xunit;
namespace LeetSharpTool.Tests
{
public class CliTests
{
[Fact]
public async Task Should_create_random_project()
{
var code = await Program.Run(new CliOptions());
code.Success.Should().BeTrue();
IsProjectExist(code.Value).Should().BeTrue();
RemoveProject(code.Value);
}
[Fact]
public async Task Should_create_random_project_with_level()
{
var code = await Program.Run(new CliOptions {Level = ProblemLevel.Hard});
code.Success.Should().BeTrue();
IsProjectExist(code.Value).Should().BeTrue();
RemoveProject(code.Value);
}
[Fact]
public async Task Should_create_project_from_url()
{
var code = await Program.Run(new CliOptions {ProblemUrl = "https://leetcode.com/problems/two-sum/"});
code.Success.Should().BeTrue();
IsProjectExist(code.Value).Should().BeTrue();
RemoveProject(code.Value);
}
[Theory]
[InlineData("https://explore.com")]
[InlineData("https://leetcode.com/problems/asd/")]
[InlineData("https://leetcode.com/problems/asd")]
public async Task Should_return_error_if_url_is_not_leetcode_problem(string url)
{
var code = await Program.Run(new CliOptions {ProblemUrl = url});
code.Success.Should().BeFalse();
IsProjectExist(code.Value).Should().BeFalse();
}
[Fact]
public async Task Should_return_error_if_problem_already_exist()
{
var prevResult = await Program.Run(new CliOptions {ProblemUrl = "https://leetcode.com/problems/two-sum/"});
var result = await Program.Run(new CliOptions {ProblemUrl = "https://leetcode.com/problems/two-sum/"});
result.Success.Should().BeFalse();
result.Error.Should().Be(ProgramErrors.ProblemAlreadyExist);
RemoveProject(prevResult.Value);
}
private static bool IsProjectExist(string path)
{
return Directory.Exists(path) && new DirectoryInfo(path).GetFiles().Length > 0;
}
private static void RemoveProject(string path)
{
Directory.Delete(path, true);
}
}
} | 31.192308 | 119 | 0.606658 | [
"MIT"
] | DenisPimenov/LeetCodeProjectTool | test/LeetSharpTool.Tests/CliTests.cs | 2,433 | C# |
using Inheritance.Enums;
using System;
using System.Collections.Generic;
using System.Text;
namespace Inheritance.Classes
{
// Dog inherits from Animal
public class Dog : Animal
{
public Dog() : base(AnimalTypes.Dog)
{
Console.WriteLine("New instance of dog is created!");
}
// This property is uniqe for Dog
public string Race { get; set; }
// Method that is unique for Dog
public void Bark()
{
Console.WriteLine("Af, af!");
}
}
}
| 20.333333 | 65 | 0.577413 | [
"MIT"
] | sedc-codecademy/skwd9-net-05-oopcsharp | G6/Class_07/Inheritance/Inheritance/Classes/Dog.cs | 551 | C# |
using System;
public class X
{
public readonly int Data;
public X testme (out int x)
{
x = 1;
return this;
}
public X ()
{
int x, y;
y = this.testme (out x).Data;
Console.WriteLine("X is {0}", x);
}
public static void Main ()
{
X x = new X ();
}
}
| 14.884615 | 49 | 0.397933 | [
"Apache-2.0"
] | 121468615/mono | mcs/tests/test-383.cs | 387 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.Azure.ServiceBus.UnitTests
{
using System;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Azure.ServiceBus.Core;
using Xunit;
public class ExpectedMessagingExceptionTests
{
[Fact]
[LiveTest]
async Task MessageLockLostExceptionTest()
{
const int messageCount = 2;
var sender = new MessageSender(TestUtility.NamespaceConnectionString, TestConstants.NonPartitionedQueueName);
var receiver = new MessageReceiver(TestUtility.NamespaceConnectionString, TestConstants.NonPartitionedQueueName, receiveMode: ReceiveMode.PeekLock);
try
{
await TestUtility.SendMessagesAsync(sender, messageCount);
var receivedMessages = await TestUtility.ReceiveMessagesAsync(receiver, messageCount);
Assert.True(receivedMessages.Count == messageCount);
// Let the messages expire
await Task.Delay(TimeSpan.FromMinutes(1));
// Complete should throw
await
Assert.ThrowsAsync<MessageLockLostException>(
async () => await TestUtility.CompleteMessagesAsync(receiver, receivedMessages));
receivedMessages = await TestUtility.ReceiveMessagesAsync(receiver, messageCount);
Assert.True(receivedMessages.Count == messageCount);
await TestUtility.CompleteMessagesAsync(receiver, receivedMessages);
}
finally
{
await sender.CloseAsync().ConfigureAwait(false);
await receiver.CloseAsync().ConfigureAwait(false);
}
}
[Fact]
[LiveTest]
async Task CompleteOnPeekedMessagesShouldThrowTest()
{
var sender = new MessageSender(TestUtility.NamespaceConnectionString, TestConstants.NonPartitionedQueueName);
var receiver = new MessageReceiver(TestUtility.NamespaceConnectionString, TestConstants.NonPartitionedQueueName, receiveMode: ReceiveMode.ReceiveAndDelete);
try
{
await TestUtility.SendMessagesAsync(sender, 1);
var message = await receiver.PeekAsync();
Assert.NotNull(message);
await
Assert.ThrowsAsync<InvalidOperationException>(
async () => await receiver.CompleteAsync(message.SystemProperties.LockToken));
message = await receiver.ReceiveAsync();
Assert.NotNull(message);
}
finally
{
await sender.CloseAsync().ConfigureAwait(false);
await receiver.CloseAsync().ConfigureAwait(false);
}
}
[Fact]
[LiveTest]
async Task SessionLockLostExceptionTest()
{
var sender = new MessageSender(TestUtility.NamespaceConnectionString, TestConstants.SessionNonPartitionedQueueName);
var sessionClient = new SessionClient(TestUtility.NamespaceConnectionString, TestConstants.SessionNonPartitionedQueueName);
try
{
var messageId = "test-message1";
var sessionId = Guid.NewGuid().ToString();
await sender.SendAsync(new Message { MessageId = messageId, SessionId = sessionId });
TestUtility.Log($"Sent Message: {messageId} to Session: {sessionId}");
var sessionReceiver = await sessionClient.AcceptMessageSessionAsync(sessionId);
Assert.NotNull(sessionReceiver);
TestUtility.Log($"Received Session: SessionId: {sessionReceiver.SessionId}: LockedUntilUtc: {sessionReceiver.LockedUntilUtc}");
var message = await sessionReceiver.ReceiveAsync();
Assert.True(message.MessageId == messageId);
TestUtility.Log($"Received Message: MessageId: {message.MessageId}");
// Let the Session expire with some buffer time
TestUtility.Log($"Waiting for session lock to time out...");
await Task.Delay((sessionReceiver.LockedUntilUtc - DateTime.UtcNow) + TimeSpan.FromSeconds(10));
await Assert.ThrowsAsync<SessionLockLostException>(async () => await sessionReceiver.ReceiveAsync());
await Assert.ThrowsAsync<SessionLockLostException>(async () => await sessionReceiver.RenewSessionLockAsync());
await Assert.ThrowsAsync<SessionLockLostException>(async () => await sessionReceiver.GetStateAsync());
await Assert.ThrowsAsync<SessionLockLostException>(async () => await sessionReceiver.SetStateAsync(null));
await Assert.ThrowsAsync<SessionLockLostException>(async () => await sessionReceiver.CompleteAsync(message.SystemProperties.LockToken));
await sessionReceiver.CloseAsync();
TestUtility.Log($"Closed Session Receiver...");
//Accept a new Session and Complete the message
sessionReceiver = await sessionClient.AcceptMessageSessionAsync(sessionId);
Assert.NotNull(sessionReceiver);
TestUtility.Log($"Received Session: SessionId: {sessionReceiver.SessionId}");
message = await sessionReceiver.ReceiveAsync();
TestUtility.Log($"Received Message: MessageId: {message.MessageId}");
await sessionReceiver.CompleteAsync(message.SystemProperties.LockToken);
await sessionReceiver.CloseAsync();
}
finally
{
await sender.CloseAsync();
await sessionClient.CloseAsync();
}
}
[Fact]
[LiveTest]
async Task OperationsOnMessageSenderReceiverAfterCloseShouldThrowObjectDisposedExceptionTest()
{
var sender = new MessageSender(TestUtility.NamespaceConnectionString, TestConstants.NonPartitionedQueueName);
var receiver = new MessageReceiver(TestUtility.NamespaceConnectionString, TestConstants.NonPartitionedQueueName, receiveMode: ReceiveMode.ReceiveAndDelete);
await sender.CloseAsync();
await receiver.CloseAsync();
await Assert.ThrowsAsync<ObjectDisposedException>(async () => await sender.SendAsync(new Message(Encoding.UTF8.GetBytes("test"))));
await Assert.ThrowsAsync<ObjectDisposedException>(async () => await receiver.ReceiveAsync());
await Assert.ThrowsAsync<ObjectDisposedException>(async () => await receiver.CompleteAsync("blah"));
}
[Fact]
[LiveTest]
async Task OperationsOnMessageSessionAfterCloseShouldThrowObjectDisposedExceptionTest()
{
var sender = new MessageSender(TestUtility.NamespaceConnectionString, TestConstants.SessionNonPartitionedQueueName);
var sessionClient = new SessionClient(TestUtility.NamespaceConnectionString, TestConstants.SessionNonPartitionedQueueName);
IMessageSession sessionReceiver = null;
try
{
var messageId = "test-message1";
var sessionId = Guid.NewGuid().ToString();
await sender.SendAsync(new Message { MessageId = messageId, SessionId = sessionId });
TestUtility.Log($"Sent Message: {messageId} to Session: {sessionId}");
sessionReceiver = await sessionClient.AcceptMessageSessionAsync(sessionId);
Assert.NotNull(sessionReceiver);
TestUtility.Log($"Received Session: SessionId: {sessionReceiver.SessionId}: LockedUntilUtc: {sessionReceiver.LockedUntilUtc}");
await sessionReceiver.CloseAsync();
await Assert.ThrowsAsync<ObjectDisposedException>(async () => await sessionReceiver.ReceiveAsync());
await Assert.ThrowsAsync<ObjectDisposedException>(async () => await sessionReceiver.GetStateAsync());
await Assert.ThrowsAsync<ObjectDisposedException>(async () => await sessionReceiver.SetStateAsync(null));
sessionReceiver = await sessionClient.AcceptMessageSessionAsync(sessionId);
Assert.NotNull(sessionReceiver);
TestUtility.Log($"Reaccept Session: SessionId: {sessionReceiver.SessionId}: LockedUntilUtc: {sessionReceiver.LockedUntilUtc}");
var message = await sessionReceiver.ReceiveAsync();
Assert.True(message.MessageId == messageId);
TestUtility.Log($"Received Message: MessageId: {message.MessageId}");
await sessionReceiver.CompleteAsync(message.SystemProperties.LockToken);
await sessionReceiver.CloseAsync();
}
finally
{
await sender.CloseAsync();
await sessionClient.CloseAsync();
}
}
}
} | 49.874317 | 168 | 0.644461 | [
"MIT"
] | Yiliu-microsoft/azure-sdk-for-net | src/SDKs/ServiceBus/data-plane/tests/Microsoft.Azure.ServiceBus.Tests/ExpectedMessagingExceptionTests.cs | 9,127 | C# |
using Net.FreeORM.Entity.Base;
using Net.FreeORM.VistaDB_TestWFA.Source.DL;
namespace Net.FreeORM.VistaDB_TestWFA.Source.BO
{
public class Roles : BaseBO
{
private int _OBJID;
public int OBJID
{
set { _OBJID = value; OnPropertyChanged("OBJID"); }
get { return _OBJID; }
}
private string _RoleName;
public string RoleName
{
set { _RoleName = value; OnPropertyChanged("RoleName"); }
get { return _RoleName; }
}
private byte _IsActive;
public byte IsActive
{
set { _IsActive = value; OnPropertyChanged("IsActive"); }
get { return _IsActive; }
}
public override string GetTableName()
{
return "Roles";
}
public override string GetIdColumn()
{
return "OBJID";
}
internal int Insert()
{
try
{
using (RolesDL _rolesdlDL = new RolesDL())
{
return _rolesdlDL.Insert(this);
}
}
catch
{
throw;
}
}
internal int InsertAndGetId()
{
try
{
using (RolesDL _rolesdlDL = new RolesDL())
{
return _rolesdlDL.InsertAndGetId(this);
}
}
catch
{
throw;
}
}
internal int Update()
{
try
{
using (RolesDL _rolesdlDL = new RolesDL())
{
return _rolesdlDL.Update(this);
}
}
catch
{
throw;
}
}
internal int Delete()
{
try
{
using (RolesDL _rolesdlDL = new RolesDL())
{
return _rolesdlDL.Delete(this);
}
}
catch
{
throw;
}
}
}
}
| 21.574257 | 69 | 0.395135 | [
"Apache-2.0"
] | mustafasacli/Net.FreeORM.Data.Repo | Net.FreeORM.Test/Net.FreeORM.VistaDB_TestWFA/Source/BO/Roles.cs | 2,179 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the application-insights-2018-11-25.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.ApplicationInsights.Model
{
/// <summary>
/// Container for the parameters to the DescribeObservation operation.
/// Describes an anomaly or error with the application.
/// </summary>
public partial class DescribeObservationRequest : AmazonApplicationInsightsRequest
{
private string _observationId;
/// <summary>
/// Gets and sets the property ObservationId.
/// <para>
/// The ID of the observation.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public string ObservationId
{
get { return this._observationId; }
set { this._observationId = value; }
}
// Check to see if ObservationId property is set
internal bool IsSetObservationId()
{
return this._observationId != null;
}
}
} | 30.706897 | 118 | 0.67041 | [
"Apache-2.0"
] | TallyUpTeam/aws-sdk-net | sdk/src/Services/ApplicationInsights/Generated/Model/DescribeObservationRequest.cs | 1,781 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// Ce code a été généré par un outil.
// Version du runtime :4.0.30319.42000
//
// Les modifications apportées à ce fichier peuvent provoquer un comportement incorrect et seront perdues si
// le code est régénéré.
// </auto-generated>
//------------------------------------------------------------------------------
///
/// This class was created from file C:\Users\loicm\GitSiriusCode\siriusquality-bioma-wheatpotentiallai-component\SiriusQuality-WheatLAI\XML\SiriusQualityWheatLAI_WheatLAIState.xml
/// The tool used was: DCC - Domain Class Coder, http://components.biomamodelling.org/, DCC
///
/// Loic Manceau
/// [email protected]
/// INRAE
///
///
/// 20/10/2020 13:24:50
///
namespace SiriusQualityWheatLAI
{
using System;
using CRA.ModelLayer.Core;
/// <summary>WheatLAIStateVarInfoClasses contain the attributes for each variable in the domain class RainData. Attributes are valorized via the static constructor. The data-type VarInfo causes a dependency to the assembly CRA.Core.Preconditions.dll</summary>
public class WheatLAIStateVarInfo : IVarInfoClass
{
#region Private fields
static VarInfo _newLeafHasAppeared = new VarInfo();
static VarInfo _leafNumber = new VarInfo();
static VarInfo _finalLeafNumber = new VarInfo();
static VarInfo _roundedFinalLeafNumber = new VarInfo();
static VarInfo _phytonum = new VarInfo();
static VarInfo _index = new VarInfo();
static VarInfo _MaximumPotentialLaminaeAI = new VarInfo();
static VarInfo _MaximumPotentialSheathAI = new VarInfo();
static VarInfo _FPAW = new VarInfo();
static VarInfo _isPotentialLAI = new VarInfo();
static VarInfo _VPDairCanopy = new VarInfo();
static VarInfo _DSF = new VarInfo();
static VarInfo _DEF = new VarInfo();
static VarInfo _cumulTTShoot = new VarInfo();
static VarInfo _deltaTTShoot = new VarInfo();
static VarInfo _deltaTTSenescence = new VarInfo();
static VarInfo _incDeltaAreaLimitSF = new VarInfo();
static VarInfo _WaterLimitedPotDeltaAIList = new VarInfo();
static VarInfo _potentialIncDeltaArea = new VarInfo();
static VarInfo _tilleringProfile = new VarInfo();
static VarInfo _leafTillerNumberArray = new VarInfo();
static VarInfo _previousIndex = new VarInfo();
static VarInfo _TTgroSheathList = new VarInfo();
static VarInfo _TT = new VarInfo();
static VarInfo _dayLength = new VarInfo();
static VarInfo _avHourVPDDay = new VarInfo();
static VarInfo _availableN = new VarInfo();
static VarInfo _incDeltaArea = new VarInfo();
#endregion
/// <summary>Constructor</summary>
static WheatLAIStateVarInfo()
{
WheatLAIStateVarInfo.DescribeVariables();
}
#region IVarInfoClass members
/// <summary>Domain Class description</summary>
public virtual string Description
{
get
{
return "Domain class description";
}
}
/// <summary>Reference to the ontology</summary>
public string URL
{
get
{
return "http://";
}
}
/// <summary>Value domain class of reference</summary>
public string DomainClassOfReference
{
get
{
return "WheatLAIState";
}
}
#endregion
#region Public properties
/// <summary>0: if no leaf has appeared, 1 if a leaf has just appeared</summary>
public static VarInfo newLeafHasAppeared
{
get
{
return _newLeafHasAppeared;
}
}
/// <summary>Number of emerged leaves on the main-stem</summary>
public static VarInfo leafNumber
{
get
{
return _leafNumber;
}
}
/// <summary> Leaf numer at maturity</summary>
public static VarInfo finalLeafNumber
{
get
{
return _finalLeafNumber;
}
}
/// <summary>rounded leaf number at maturity</summary>
public static VarInfo roundedFinalLeafNumber
{
get
{
return _roundedFinalLeafNumber;
}
}
/// <summary>Number of leaf layer created</summary>
public static VarInfo phytonum
{
get
{
return _phytonum;
}
}
/// <summary>index of the last leaf layer created</summary>
public static VarInfo index
{
get
{
return _index;
}
}
/// <summary>Maximum allowed Lamina area index without stress effects</summary>
public static VarInfo MaximumPotentialLaminaeAI
{
get
{
return _MaximumPotentialLaminaeAI;
}
}
/// <summary>Maximum Sheat area index allowed without stress effect</summary>
public static VarInfo MaximumPotentialSheathAI
{
get
{
return _MaximumPotentialSheathAI;
}
}
/// <summary>Fraction of plant available water</summary>
public static VarInfo FPAW
{
get
{
return _FPAW;
}
}
/// <summary>0: no drought stress is applied, 1: drought stress is applied</summary>
public static VarInfo isPotentialLAI
{
get
{
return _isPotentialLAI;
}
}
/// <summary>Vapour Pressur deficit Air-Canopy</summary>
public static VarInfo VPDairCanopy
{
get
{
return _VPDairCanopy;
}
}
/// <summary>drought senescence factor</summary>
public static VarInfo DSF
{
get
{
return _DSF;
}
}
/// <summary>drought expansion factor</summary>
public static VarInfo DEF
{
get
{
return _DEF;
}
}
/// <summary>Cumulative Shoot thermal time</summary>
public static VarInfo cumulTTShoot
{
get
{
return _cumulTTShoot;
}
}
/// <summary>Increas of shoot thermal time for the day</summary>
public static VarInfo deltaTTShoot
{
get
{
return _deltaTTShoot;
}
}
/// <summary>Increase of senescence thermal time for the day</summary>
public static VarInfo deltaTTSenescence
{
get
{
return _deltaTTSenescence;
}
}
/// <summary>Total daily increase of GAI under drought stress</summary>
public static VarInfo incDeltaAreaLimitSF
{
get
{
return _incDeltaAreaLimitSF;
}
}
/// <summary>list on each phytomer for the potential daily increase of leaf layer</summary>
public static VarInfo WaterLimitedPotDeltaAIList
{
get
{
return _WaterLimitedPotDeltaAIList;
}
}
/// <summary>Total daily increase in GAI without stress</summary>
public static VarInfo potentialIncDeltaArea
{
get
{
return _potentialIncDeltaArea;
}
}
/// <summary>store the amount of new tiller created at each time a new tiller appears</summary>
public static VarInfo tilleringProfile
{
get
{
return _tilleringProfile;
}
}
/// <summary>store the number of tiller for each leaf layer</summary>
public static VarInfo leafTillerNumberArray
{
get
{
return _leafTillerNumberArray;
}
}
/// <summary>index of the leaf layer during the last call of the component</summary>
public static VarInfo previousIndex
{
get
{
return _previousIndex;
}
}
/// <summary>List of Thermal Time at end of the sheath growth</summary>
public static VarInfo TTgroSheathList
{
get
{
return _TTgroSheathList;
}
}
/// <summary>List of Thermal times since emergence of this leaf Layer</summary>
public static VarInfo TT
{
get
{
return _TT;
}
}
/// <summary>Lenght of the day</summary>
public static VarInfo dayLength
{
get
{
return _dayLength;
}
}
/// <summary>Average VPD during the day</summary>
public static VarInfo avHourVPDDay
{
get
{
return _avHourVPDDay;
}
}
/// <summary>Available Nitrogen of the day</summary>
public static VarInfo availableN
{
get
{
return _availableN;
}
}
/// <summary>Actual increase in Area of the day</summary>
public static VarInfo incDeltaArea
{
get
{
return _incDeltaArea;
}
}
#endregion
#region VarInfo values
/// <summary>Set VarInfo values</summary>
static void DescribeVariables()
{
//
_newLeafHasAppeared.Name = "newLeafHasAppeared";
_newLeafHasAppeared.Description = "0: if no leaf has appeared, 1 if a leaf has just appeared";
_newLeafHasAppeared.MaxValue = 1D;
_newLeafHasAppeared.MinValue = 0D;
_newLeafHasAppeared.DefaultValue = 0D;
_newLeafHasAppeared.Units = "NA";
_newLeafHasAppeared.URL = "http://";
_newLeafHasAppeared.ValueType = VarInfoValueTypes.GetInstanceForName("Integer");
//
_leafNumber.Name = "leafNumber";
_leafNumber.Description = "Number of emerged leaves on the main-stem";
_leafNumber.MaxValue = 20D;
_leafNumber.MinValue = 0D;
_leafNumber.DefaultValue = 0D;
_leafNumber.Units = "leaf";
_leafNumber.URL = "http://";
_leafNumber.ValueType = VarInfoValueTypes.GetInstanceForName("Double");
//
_finalLeafNumber.Name = "finalLeafNumber";
_finalLeafNumber.Description = " Leaf numer at maturity";
_finalLeafNumber.MaxValue = 20D;
_finalLeafNumber.MinValue = 0D;
_finalLeafNumber.DefaultValue = 10D;
_finalLeafNumber.Units = "leaf";
_finalLeafNumber.URL = "http://";
_finalLeafNumber.ValueType = VarInfoValueTypes.GetInstanceForName("Double");
//
_roundedFinalLeafNumber.Name = "roundedFinalLeafNumber";
_roundedFinalLeafNumber.Description = "rounded leaf number at maturity";
_roundedFinalLeafNumber.MaxValue = 20D;
_roundedFinalLeafNumber.MinValue = 0D;
_roundedFinalLeafNumber.DefaultValue = 10D;
_roundedFinalLeafNumber.Units = "leaf";
_roundedFinalLeafNumber.URL = "http://";
_roundedFinalLeafNumber.ValueType = VarInfoValueTypes.GetInstanceForName("Integer");
//
_phytonum.Name = "phytonum";
_phytonum.Description = "Number of leaf layer created";
_phytonum.MaxValue = 21D;
_phytonum.MinValue = 1D;
_phytonum.DefaultValue = 1D;
_phytonum.Units = "-";
_phytonum.URL = "http://";
_phytonum.ValueType = VarInfoValueTypes.GetInstanceForName("Integer");
//
_index.Name = "index";
_index.Description = "index of the last leaf layer created";
_index.MaxValue = 20D;
_index.MinValue = 0D;
_index.DefaultValue = 0D;
_index.Units = "-";
_index.URL = "http://";
_index.ValueType = VarInfoValueTypes.GetInstanceForName("Integer");
//
_MaximumPotentialLaminaeAI.Name = "MaximumPotentialLaminaeAI";
_MaximumPotentialLaminaeAI.Description = "Maximum allowed Lamina area index without stress effects";
_MaximumPotentialLaminaeAI.MaxValue = 100D;
_MaximumPotentialLaminaeAI.MinValue = 0D;
_MaximumPotentialLaminaeAI.DefaultValue = 0D;
_MaximumPotentialLaminaeAI.Units = "m²/m²";
_MaximumPotentialLaminaeAI.URL = "http://";
_MaximumPotentialLaminaeAI.ValueType = VarInfoValueTypes.GetInstanceForName("ListDouble");
//
_MaximumPotentialSheathAI.Name = "MaximumPotentialSheathAI";
_MaximumPotentialSheathAI.Description = "Maximum Sheat area index allowed without stress effect";
_MaximumPotentialSheathAI.MaxValue = 100D;
_MaximumPotentialSheathAI.MinValue = 0D;
_MaximumPotentialSheathAI.DefaultValue = 0D;
_MaximumPotentialSheathAI.Units = "m²/m²";
_MaximumPotentialSheathAI.URL = "http://";
_MaximumPotentialSheathAI.ValueType = VarInfoValueTypes.GetInstanceForName("ListDouble");
//
_FPAW.Name = "FPAW";
_FPAW.Description = "Fraction of plant available water";
_FPAW.MaxValue = 1D;
_FPAW.MinValue = 0D;
_FPAW.DefaultValue = 0.5D;
_FPAW.Units = "dimensionless";
_FPAW.URL = "http://";
_FPAW.ValueType = VarInfoValueTypes.GetInstanceForName("Double");
//
_isPotentialLAI.Name = "isPotentialLAI";
_isPotentialLAI.Description = "0: no drought stress is applied, 1: drought stress is applied";
_isPotentialLAI.MaxValue = 1D;
_isPotentialLAI.MinValue = 0D;
_isPotentialLAI.DefaultValue = 0D;
_isPotentialLAI.Units = "-";
_isPotentialLAI.URL = "http://";
_isPotentialLAI.ValueType = VarInfoValueTypes.GetInstanceForName("Integer");
//
_VPDairCanopy.Name = "VPDairCanopy";
_VPDairCanopy.Description = "Vapour Pressur deficit Air-Canopy";
_VPDairCanopy.MaxValue = 100D;
_VPDairCanopy.MinValue = 0D;
_VPDairCanopy.DefaultValue = 0D;
_VPDairCanopy.Units = "hPa";
_VPDairCanopy.URL = "http://";
_VPDairCanopy.ValueType = VarInfoValueTypes.GetInstanceForName("Double");
//
_DSF.Name = "DSF";
_DSF.Description = "drought senescence factor";
_DSF.MaxValue = 10D;
_DSF.MinValue = 0D;
_DSF.DefaultValue = 0D;
_DSF.Units = "-";
_DSF.URL = "http://";
_DSF.ValueType = VarInfoValueTypes.GetInstanceForName("Double");
//
_DEF.Name = "DEF";
_DEF.Description = "drought expansion factor";
_DEF.MaxValue = 10D;
_DEF.MinValue = 0D;
_DEF.DefaultValue = 0D;
_DEF.Units = "-";
_DEF.URL = "http://";
_DEF.ValueType = VarInfoValueTypes.GetInstanceForName("Double");
//
_cumulTTShoot.Name = "cumulTTShoot";
_cumulTTShoot.Description = "Cumulative Shoot thermal time";
_cumulTTShoot.MaxValue = 1000D;
_cumulTTShoot.MinValue = 0D;
_cumulTTShoot.DefaultValue = 0D;
_cumulTTShoot.Units = "°C/d";
_cumulTTShoot.URL = "http://";
_cumulTTShoot.ValueType = VarInfoValueTypes.GetInstanceForName("Double");
//
_deltaTTShoot.Name = "deltaTTShoot";
_deltaTTShoot.Description = "Increas of shoot thermal time for the day";
_deltaTTShoot.MaxValue = 50D;
_deltaTTShoot.MinValue = 0D;
_deltaTTShoot.DefaultValue = 0D;
_deltaTTShoot.Units = "°C/d";
_deltaTTShoot.URL = "http://";
_deltaTTShoot.ValueType = VarInfoValueTypes.GetInstanceForName("Double");
//
_deltaTTSenescence.Name = "deltaTTSenescence";
_deltaTTSenescence.Description = "Increase of senescence thermal time for the day";
_deltaTTSenescence.MaxValue = 50D;
_deltaTTSenescence.MinValue = 0D;
_deltaTTSenescence.DefaultValue = 0D;
_deltaTTSenescence.Units = "°C/d";
_deltaTTSenescence.URL = "http://";
_deltaTTSenescence.ValueType = VarInfoValueTypes.GetInstanceForName("Double");
//
_incDeltaAreaLimitSF.Name = "incDeltaAreaLimitSF";
_incDeltaAreaLimitSF.Description = "Total daily increase of GAI under drought stress";
_incDeltaAreaLimitSF.MaxValue = 1D;
_incDeltaAreaLimitSF.MinValue = 0D;
_incDeltaAreaLimitSF.DefaultValue = 0D;
_incDeltaAreaLimitSF.Units = "m²/m²";
_incDeltaAreaLimitSF.URL = "http://";
_incDeltaAreaLimitSF.ValueType = VarInfoValueTypes.GetInstanceForName("Double");
//
_WaterLimitedPotDeltaAIList.Name = "WaterLimitedPotDeltaAIList";
_WaterLimitedPotDeltaAIList.Description = "list on each phytomer for the potential daily increase of leaf layer";
_WaterLimitedPotDeltaAIList.MaxValue = 0D;
_WaterLimitedPotDeltaAIList.MinValue = 0D;
_WaterLimitedPotDeltaAIList.DefaultValue = 0D;
_WaterLimitedPotDeltaAIList.Units = "m²/m²";
_WaterLimitedPotDeltaAIList.URL = "http://";
_WaterLimitedPotDeltaAIList.ValueType = VarInfoValueTypes.GetInstanceForName("ListDouble");
//
_potentialIncDeltaArea.Name = "potentialIncDeltaArea";
_potentialIncDeltaArea.Description = "Total daily increase in GAI without stress";
_potentialIncDeltaArea.MaxValue = 10D;
_potentialIncDeltaArea.MinValue = 0D;
_potentialIncDeltaArea.DefaultValue = 0D;
_potentialIncDeltaArea.Units = "m²/m²";
_potentialIncDeltaArea.URL = "http://";
_potentialIncDeltaArea.ValueType = VarInfoValueTypes.GetInstanceForName("Double");
//
_tilleringProfile.Name = "tilleringProfile";
_tilleringProfile.Description = "store the amount of new tiller created at each time a new tiller appears";
_tilleringProfile.MaxValue = 0D;
_tilleringProfile.MinValue = 0D;
_tilleringProfile.DefaultValue = 0D;
_tilleringProfile.Units = "shoot/m²";
_tilleringProfile.URL = "http://";
_tilleringProfile.ValueType = VarInfoValueTypes.GetInstanceForName("ListDouble");
//
_leafTillerNumberArray.Name = "leafTillerNumberArray";
_leafTillerNumberArray.Description = "store the number of tiller for each leaf layer";
_leafTillerNumberArray.MaxValue = 0D;
_leafTillerNumberArray.MinValue = 0D;
_leafTillerNumberArray.DefaultValue = 0D;
_leafTillerNumberArray.Units = "shoot";
_leafTillerNumberArray.URL = "http://";
_leafTillerNumberArray.ValueType = VarInfoValueTypes.GetInstanceForName("ListDouble");
//
_previousIndex.Name = "previousIndex";
_previousIndex.Description = "index of the leaf layer during the last call of the component";
_previousIndex.MaxValue = 20D;
_previousIndex.MinValue = 0D;
_previousIndex.DefaultValue = 0D;
_previousIndex.Units = "dimensioonless";
_previousIndex.URL = "http://";
_previousIndex.ValueType = VarInfoValueTypes.GetInstanceForName("Integer");
//
_TTgroSheathList.Name = "TTgroSheathList";
_TTgroSheathList.Description = "List of Thermal Time at end of the sheath growth";
_TTgroSheathList.MaxValue = 3000D;
_TTgroSheathList.MinValue = 0D;
_TTgroSheathList.DefaultValue = 0D;
_TTgroSheathList.Units = "°Cd";
_TTgroSheathList.URL = "http://";
_TTgroSheathList.ValueType = VarInfoValueTypes.GetInstanceForName("ListDouble");
//
_TT.Name = "TT";
_TT.Description = "List of Thermal times since emergence of this leaf Layer";
_TT.MaxValue = 3000D;
_TT.MinValue = 0D;
_TT.DefaultValue = 0D;
_TT.Units = "°Cd";
_TT.URL = "http://";
_TT.ValueType = VarInfoValueTypes.GetInstanceForName("ListDouble");
//
_dayLength.Name = "dayLength";
_dayLength.Description = "Lenght of the day";
_dayLength.MaxValue = 24D;
_dayLength.MinValue = 0D;
_dayLength.DefaultValue = 12D;
_dayLength.Units = "h";
_dayLength.URL = "http://";
_dayLength.ValueType = VarInfoValueTypes.GetInstanceForName("Double");
//
_avHourVPDDay.Name = "avHourVPDDay";
_avHourVPDDay.Description = "Average VPD during the day";
_avHourVPDDay.MaxValue = 100D;
_avHourVPDDay.MinValue = 0D;
_avHourVPDDay.DefaultValue = 0D;
_avHourVPDDay.Units = "hPa";
_avHourVPDDay.URL = "http://";
_avHourVPDDay.ValueType = VarInfoValueTypes.GetInstanceForName("Double");
//
_availableN.Name = "availableN";
_availableN.Description = "Available Nitrogen of the day";
_availableN.MaxValue = 1000D;
_availableN.MinValue = 0D;
_availableN.DefaultValue = 10D;
_availableN.Units = "g/m²";
_availableN.URL = "http://";
_availableN.ValueType = VarInfoValueTypes.GetInstanceForName("Double");
//
_incDeltaArea.Name = "incDeltaArea";
_incDeltaArea.Description = "Actual increase in Area of the day";
_incDeltaArea.MaxValue = 1000D;
_incDeltaArea.MinValue = 0D;
_incDeltaArea.DefaultValue = 0D;
_incDeltaArea.Units = "m²/m²";
_incDeltaArea.URL = "http://";
_incDeltaArea.ValueType = VarInfoValueTypes.GetInstanceForName("Double");
}
#endregion
}
}
| 37.228482 | 264 | 0.555173 | [
"MIT"
] | SiriusQuality/SiriusQuality-BioMa-WheatPotentialLAI-Component | SiriusQuality-WheatLAI/domainClass/WheatLAIStateVarInfo.cs | 23,819 | 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 Telerik.Web.UI;
namespace DotNetNuke.Web.UI.WebControls
{
class DnnScriptManager : RadScriptManager
{
}
}
| 23.2 | 72 | 0.735632 | [
"MIT"
] | MaiklT/Dnn.Platform | DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnScriptManager.cs | 350 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
public class ModelHelper : MonoBehaviour
{
public bool self_collide = false;
public List<GameObject> links = new List<GameObject>();
public List<ModelHelper> models = new List<ModelHelper>();
void Awake()
{
if (self_collide == false)
{
var childLinkBodies = links.SelectMany(t => t.GetComponentsInChildren<Collider>());
var subModelBodies =
models.SelectMany(m => m.links)
.SelectMany(l => l.GetComponentsInChildren<Collider>());
foreach (var body in childLinkBodies)
{
foreach (var sBody in subModelBodies)
{
Physics.IgnoreCollision(body, sBody);
}
}
}
for (int i = 0; i < links.Count; i++)
{
var link1 = links[i].GetComponent<LinkHelper>();
for (int j = i + 1; j < links.Count; j++)
{
var link2 = links[j].GetComponent<LinkHelper>();
bool shouldCollide = self_collide || link1.self_collide || link2.self_collide;
/* model/self_collide :
If set to true, all links in the model will collide with each other (except those connected by a joint). Can be overridden by the link or collision element self_collide property. Two links within a model will collide if link1.self_collide OR link2.self_collide. Links connected by a joint will never collide.
*/
if (!shouldCollide)
{
var link1Bodies = link1.GetComponentsInChildren<Collider>();
var link2Bodies = link2.GetComponentsInChildren<Collider>();
foreach (var body1 in link1Bodies)
{
foreach (var body2 in link2Bodies)
{
Physics.IgnoreCollision(body1, body2);
}
}
}
}
}
}
}
| 38.403509 | 325 | 0.523984 | [
"Apache-2.0",
"BSD-3-Clause"
] | Carteav/simulator | Assets/Scripts/Utilities/SDF/ModelHelper.cs | 2,189 | 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("Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Tests")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("ea689eb8-488b-4dce-9ddd-c645d68a3d3d")]
// 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.378378 | 84 | 0.742589 | [
"Apache-2.0"
] | sarochm/ltc | LoginTimeControl/Tests/Properties/AssemblyInfo.cs | 1,386 | C# |
using NUnit.Framework;
namespace Matrix.Tests
{
[TestFixture]
public class ExampleTests
{
[Test]
public void TestATest()
{
Assert.That(1, Is.EqualTo(1));
}
}
}
| 15.066667 | 41 | 0.517699 | [
"MIT"
] | Hourouheki/matrix-dotnet-sdk | Matrix.Tests/MatrixTests.cs | 228 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/d3d12.h in the Windows SDK for Windows 10.0.22000.0
// Original source is Copyright © Microsoft. All rights reserved.
namespace TerraFX.Interop.DirectX;
/// <include file='D3D12_TEX2D_ARRAY_UAV.xml' path='doc/member[@name="D3D12_TEX2D_ARRAY_UAV"]/*' />
public partial struct D3D12_TEX2D_ARRAY_UAV
{
/// <include file='D3D12_TEX2D_ARRAY_UAV.xml' path='doc/member[@name="D3D12_TEX2D_ARRAY_UAV.MipSlice"]/*' />
public uint MipSlice;
/// <include file='D3D12_TEX2D_ARRAY_UAV.xml' path='doc/member[@name="D3D12_TEX2D_ARRAY_UAV.FirstArraySlice"]/*' />
public uint FirstArraySlice;
/// <include file='D3D12_TEX2D_ARRAY_UAV.xml' path='doc/member[@name="D3D12_TEX2D_ARRAY_UAV.ArraySize"]/*' />
public uint ArraySize;
/// <include file='D3D12_TEX2D_ARRAY_UAV.xml' path='doc/member[@name="D3D12_TEX2D_ARRAY_UAV.PlaneSlice"]/*' />
public uint PlaneSlice;
}
| 45.521739 | 145 | 0.74212 | [
"MIT"
] | reflectronic/terrafx.interop.windows | sources/Interop/Windows/DirectX/um/d3d12/D3D12_TEX2D_ARRAY_UAV.cs | 1,049 | C# |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using ArkSaveAnalyzer.Infrastructure;
using ArkSaveAnalyzer.Infrastructure.Messages;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.CommandWpf;
using GalaSoft.MvvmLight.Messaging;
using Microsoft.Win32;
using SavegameToolkit;
using SavegameToolkitAdditions;
namespace ArkSaveAnalyzer.Maps {
public class MapViewModel : ViewModelBase {
private string currentMapName;
private bool mapStyleTopographic;
private string fileName;
private string sortColumn;
private readonly Dictionary<string, ListSortDirection> sortDirectionsTames = new Dictionary<string, ListSortDirection>();
private readonly Dictionary<string, ListSortDirection> sortDirectionsStructuresFlatList = new Dictionary<string, ListSortDirection>();
public RelayCommand<string> MapCommand { get; }
public RelayCommand OpenFileCommand { get; }
public RelayCommand<GameObject> ShowDataTameCommand { get; }
public RelayCommand<StructuresViewModel> ShowDataStructuresCommand { get; }
public RelayCommand<StructureViewModel> ShowDataStructureCommand { get; }
public RelayCommand MapStyleCommand { get; }
public RelayCommand<string> SortTamesCommand { get; set; }
public RelayCommand<string> SortStructuresFlatCommand { get; set; }
public ObservableCollection<GameObject> Tames { get; } = new ObservableCollection<GameObject>();
public ObservableCollection<CreatureViewModel> Creatures { get; } = new ObservableCollection<CreatureViewModel>();
public ObservableCollection<StructuresViewModel> Structures { get; } = new ObservableCollection<StructuresViewModel>();
public ObservableCollection<StructureViewModel> StructureFlatList { get; } = new ObservableCollection<StructureViewModel>();
#region UiEnabled
private bool uiEnabled = true;
public bool UiEnabled {
get => uiEnabled;
set {
if (Set(ref uiEnabled, value))
CommandManager.InvalidateRequerySuggested();
}
}
#endregion
#region MapImage
private ImageSource mapImage;
public ImageSource MapImage {
get => mapImage;
set => Set(ref mapImage, value);
}
#endregion
#region MapData
private MapData mapData;
public MapData MapData {
get => mapData;
set => Set(ref mapData, value);
}
#endregion
#region MapBoundary
private Rect mapBoundary;
public Rect MapBoundary {
get => mapBoundary;
set => Set(ref mapBoundary, value);
}
#endregion
#region SelectedTame
private GameObject selectedTame;
public GameObject SelectedTame {
get => selectedTame;
set => Set(ref selectedTame, value);
}
#endregion
#region SelectedStructures
private StructuresViewModel selectedStructures;
public StructuresViewModel SelectedStructures {
get => selectedStructures;
set => Set(ref selectedStructures, value);
}
#endregion
#region SelectedStructure
private StructureViewModel selectedStructure;
public StructureViewModel SelectedStructure {
get => selectedStructure;
set => Set(ref selectedStructure, value);
}
#endregion
#region Filter
private string filter;
public string Filter {
get => filter;
set {
if (Set(ref filter, value)) {
map(currentMapName);
}
}
}
private bool filterIsRegExp;
public bool FilterIsRegExp {
get => filterIsRegExp;
set {
if (Set(ref filterIsRegExp, value)) {
map(currentMapName);
}
}
}
#endregion
public MapViewModel() {
mapData = MapData.For(null);
mapBoundary = MapData.BoundaryArtistic;
MapCommand = new RelayCommand<string>(mapName => map(mapName), s => UiEnabled);
OpenFileCommand = new RelayCommand(openFile, () => UiEnabled && !string.IsNullOrEmpty(currentMapName));
ShowDataTameCommand = new RelayCommand<GameObject>(showDataTame, m => UiEnabled);
ShowDataStructuresCommand = new RelayCommand<StructuresViewModel>(showDataStructures, m => UiEnabled);
ShowDataStructureCommand = new RelayCommand<StructureViewModel>(showDataStructure, m => UiEnabled);
MapStyleCommand = new RelayCommand(changeMapStyle, () => UiEnabled);
SortTamesCommand = new RelayCommand<string>(changeSortTames, s => UiEnabled);
SortStructuresFlatCommand = new RelayCommand<string>(changeSortStructuresFlat, s => UiEnabled);
}
private void changeSortTames(string column) {
changeSort(column, sortDirectionsTames);
List<GameObject> sortedObjects = Tames.ToList();
sortedObjects.Sort((a, b) => comparison(a, b, column, sortDirectionsTames));
Tames.Clear();
foreach (GameObject gameObject in sortedObjects) {
Tames.Add(gameObject);
}
}
private void changeSortStructuresFlat(string column) {
changeSort(column, sortDirectionsStructuresFlatList);
List<StructureViewModel> sortedObjects = StructureFlatList.ToList();
sortedObjects.Sort((a, b) => comparison(a.Structure, b.Structure, column, sortDirectionsStructuresFlatList));
StructureFlatList.Clear();
foreach (StructureViewModel structure in sortedObjects) {
StructureFlatList.Add(structure);
}
}
private void changeSort(string column, Dictionary<string, ListSortDirection> sortDirections) {
if (column == sortColumn) {
if (sortDirections.TryGetValue(column, out ListSortDirection dir)) {
if (dir == ListSortDirection.Ascending) {
sortDirections[column] = ListSortDirection.Descending;
} else if (dir == ListSortDirection.Descending) {
sortDirections.Remove(column);
}
} else {
sortDirections[column] = ListSortDirection.Ascending;
}
} else {
sortColumn = column;
sortDirections[column] = ListSortDirection.Ascending;
}
}
private int comparison(GameObject a, GameObject b, string column, Dictionary<string, ListSortDirection> sortDirections) {
ArkData arkData = ArkDataService.ArkData;
int cmp = 0;
switch (column ?? sortColumn) {
case "Location":
cmp = (int)(Math.Round(a.Location.Y, 2) - Math.Round(b.Location.Y, 2));
if (cmp == 0) {
cmp = (int)(Math.Round(a.Location.X, 2) - Math.Round(b.Location.X, 2));
}
break;
case "Id":
cmp = a.Id - b.Id;
break;
case "Creature":
cmp = string.Compare(a.GetNameForCreature(arkData), b.GetNameForCreature(arkData), StringComparison.InvariantCulture);
break;
case "Name":
cmp = string.Compare(a.GetPropertyValue<string>("TamedName"), b.GetPropertyValue<string>("TamedName"), StringComparison.InvariantCulture);
break;
case "Level":
cmp = a.GetBaseLevel() - b.GetBaseLevel();
break;
case "Sex":
cmp = (a.IsFemale() ? 1 : 0) - (b.IsFemale() ? 1 : 0);
break;
case "Tamer":
cmp = string.Compare(a.GetPropertyValue<string>("TamerString"), b.GetPropertyValue<string>("TamerString"), StringComparison.InvariantCulture);
if (cmp == 0) {
cmp = string.Compare(a.GetPropertyValue<string>("ImprinterName"), b.GetPropertyValue<string>("ImprinterName"), StringComparison.InvariantCulture);
}
break;
case "Lat":
double aLat = 0, bLat = 0;
if (a.Location != null) {
aLat = a.Location.Y / mapData.LatDiv + mapData.LatShift;
}
if (b.Location != null) {
bLat = b.Location.Y / mapData.LatDiv + mapData.LatShift;
}
cmp = Math.Sign(aLat - bLat);
break;
case "Lon":
double aLon = 0, bLon = 0;
if (a.Location != null) {
aLon = a.Location.X / mapData.LonDiv + mapData.LonShift;
}
if (b.Location != null) {
bLon = b.Location.X / mapData.LonDiv + mapData.LonShift;
}
cmp = Math.Sign(aLon - bLon);
break;
case "Hidden":
cmp = a.GetPropertyValue<bool>("IsHidden") ? 1 : 0 - (b.GetPropertyValue<bool>("IsHidden") ? 1 : 0);
break;
case "Structure Name":
cmp = string.Compare(a.GetNameForStructure(ArkDataService.ArkData) ?? a.ClassString, b.GetNameForStructure(ArkDataService.ArkData) ?? b.ClassString, StringComparison.InvariantCulture);
break;
}
if (!string.IsNullOrEmpty(column)) {
return cmp;
}
if (sortDirections.TryGetValue(sortColumn, out ListSortDirection dir)) {
if (cmp != 0) {
return dir == ListSortDirection.Ascending ? cmp : -cmp;
}
}
//foreach (KeyValuePair<string, ListSortDirection> sortDirection in sortDirections)
//{
// if (sortDirection.Key == sortColumn)
// continue;
// if (sortDirections.TryGetValue(sortDirection.Key, out dir))
// {
// cmp = comparison(a, b, sortDirection.Key, sortDirections);
// if (cmp != 0)
// {
// return dir == ListSortDirection.Ascending ? cmp : -cmp;
// }
// }
//}
return 0;
}
private void openFile() {
OpenFileDialog openFileDialog = new OpenFileDialog {
FileName = fileName,
CheckFileExists = true
};
if (openFileDialog.ShowDialog() == true) {
fileName = openFileDialog.FileName;
// todo get map name from user input
map(currentMapName, fileName);
}
}
private void changeMapStyle() {
mapStyleTopographic = !mapStyleTopographic;
setMap(currentMapName);
}
private void showDataTame(GameObject gameObject) {
if (gameObject != null) {
Messenger.Default.Send(new ShowGameObjectMessage(gameObject));
}
}
private void showDataStructures(StructuresViewModel structuresViewModel) {
if (structuresViewModel.Structures != null) {
Messenger.Default.Send(new ShowGameObjectListMessage(structuresViewModel.Structures, MapData,
string.Format(CultureInfo.InvariantCulture, "{0:0.#} / {1:0.#}", structuresViewModel.Lat, structuresViewModel.Lon)));
}
}
private void showDataStructure(StructureViewModel structureViewModel) {
if (structureViewModel.Structure != null) {
Messenger.Default.Send(new ShowGameObjectMessage(structureViewModel.Structure,
string.Format(CultureInfo.InvariantCulture, "{0:0.#} / {1:0.#} - {2}", structureViewModel.Lat, structureViewModel.Lon, structureViewModel.StructureName)));
}
}
private async void map(string mapName, string filename = null) {
UiEnabled = false;
currentMapName = mapName;
try {
Tames.Clear();
foreach (GameObject gameObject in (await MapService.ReadTames(mapName, filename)).Where(gameObject => gameObject != null)) {
if (!string.IsNullOrWhiteSpace(filter)) {
string name = gameObject.GetNameForCreature(ArkDataService.ArkData) ?? gameObject?.ClassString;
if (filterIsRegExp && !Regex.IsMatch(name, filter)) {
continue;
}
if (!name.ToLowerInvariant().Contains(filter.ToLowerInvariant())) {
continue;
}
}
Tames.Add(gameObject);
}
SelectedTame = Tames.FirstOrDefault();
setMap(mapName);
Creatures.Clear();
foreach (GameObject gameObject in Tames.Where(gameObject => gameObject != null)) {
if (!string.IsNullOrWhiteSpace(filter)) {
string name = gameObject.GetNameForCreature(ArkDataService.ArkData) ?? gameObject?.ClassString;
if (filterIsRegExp && !Regex.IsMatch(name, filter)) {
continue;
}
if (!name.ToLowerInvariant().Contains(filter.ToLowerInvariant())) {
continue;
}
}
Creatures.Add(new CreatureViewModel(gameObject));
}
Structures.Clear();
foreach (StructuresViewModel structuresViewModel in await MapService.ReadStructures(mapName, filename)) {
GameObject gameObject = structuresViewModel.Structures.FirstOrDefault();
if (gameObject == null)
continue;
if (!string.IsNullOrWhiteSpace(filter)) {
if (filterIsRegExp && !Regex.IsMatch(structuresViewModel.UniqueStructureNames, filter)) {
continue;
}
if (!structuresViewModel.UniqueStructureNames.ToLowerInvariant().Contains(filter.ToLowerInvariant())) {
continue;
}
}
Structures.Add(structuresViewModel);
}
SelectedStructures = Structures.FirstOrDefault();
StructureFlatList.Clear();
foreach (StructureViewModel structureViewModel in await MapService.ReadStructuresFlat(mapName, filename)) {
GameObject gameObject = structureViewModel.Structure;
if (gameObject == null)
continue;
if (!string.IsNullOrWhiteSpace(filter)) {
if (filterIsRegExp && !Regex.IsMatch(structureViewModel.StructureName, filter)) {
continue;
}
if (!structureViewModel.StructureName.ToLowerInvariant().Contains(filter.ToLowerInvariant())) {
continue;
}
}
StructureFlatList.Add(structureViewModel);
}
SelectedStructure = StructureFlatList.FirstOrDefault();
} catch (Exception e) {
MessageBox.Show(e.Message);
}
UiEnabled = true;
}
private void setMap(string mapName) {
if (string.IsNullOrEmpty(mapName))
return;
string imgFilename = $"pack://application:,,,/assets/{(mapStyleTopographic ? $"{mapName}_Topographic.jpg" : $"{mapName}.jpg")}";
try {
MapImage = new ImageSourceConverter().ConvertFromString(imgFilename) as ImageSource;
MapData = MapData.For(mapName);
MapBoundary = mapStyleTopographic ? MapData.BoundaryTopographic : MapData.BoundaryArtistic;
} catch (Exception e) {
MessageBox.Show(e.Message);
}
}
}
}
| 40.195853 | 205 | 0.536887 | [
"MIT"
] | Flachdachs/ArkSaveAnalyzer | ArkSaveAnalyzer/Maps/MapViewModel.cs | 17,447 | C# |
//-----------------------------------------------------------------------
// <copyright file="PropertyInfoRoot.cs" company="Marimer LLC">
// Copyright (c) Marimer LLC. All rights reserved.
// Website: https://cslanet.com
// </copyright>
// <summary>Note: We exposed the PropertyInfo's so we can test it...</summary>
//-----------------------------------------------------------------------
using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
namespace Csla.Test.PropertyInfo
{
[Serializable()]
public class PropertyInfoRoot : BusinessBase<PropertyInfoRoot>
{
#region Factory Methods
public static PropertyInfoRoot NewPropertyInfoRoot()
{
return Csla.DataPortal.Create<PropertyInfoRoot>();
}
#endregion
#region DataPortal Methods
protected override void DataPortal_Create()
{
}
#endregion
/// <summary>
/// Note: We exposed the PropertyInfo's so we can test it...
/// </summary>
#region Properties
public static readonly PropertyInfo<System.String> _nameProperty = RegisterProperty<System.String>(p => p.Name);
public System.String Name
{
get { return GetProperty(_nameProperty); }
set { SetProperty(_nameProperty, value); }
}
public static readonly PropertyInfo<System.String> _nameDataAnnotationsProperty = RegisterProperty<System.String>(p => p.NameDataAnnotations);
[Display(Name = "Name: DataAnnotations")]
public System.String NameDataAnnotations
{
get { return GetProperty(_nameDataAnnotationsProperty); }
set { SetProperty(_nameDataAnnotationsProperty, value); }
}
public static readonly PropertyInfo<System.String> _nameComponentModelProperty = RegisterProperty<System.String>(p => p.NameComponentModel);
[DisplayName("Name: ComponentModel")]
public System.String NameComponentModel
{
get { return GetProperty(_nameComponentModelProperty); }
set { SetProperty(_nameComponentModelProperty, value); }
}
public static readonly PropertyInfo<System.String> _nameFriendlyNameProperty = RegisterProperty<System.String>(p => p.NameFriendlyName, "Name: Friendly Name");
public System.String NameFriendlyName
{
get { return GetProperty(_nameFriendlyNameProperty); }
set { SetProperty(_nameFriendlyNameProperty, value); }
}
public static readonly PropertyInfo<string> NameDefaultValueProperty = RegisterProperty<string>(c => c.NameDefaultValue, string.Empty, "x");
public string NameDefaultValue
{
get { return GetProperty(NameDefaultValueProperty); }
set { SetProperty(NameDefaultValueProperty, value); }
}
public static readonly PropertyInfo<string> StringNullDefaultValueProperty = RegisterProperty<string>(c => c.StringNullDefaultValue, string.Empty, null);
public string StringNullDefaultValue
{
get { return GetProperty(StringNullDefaultValueProperty); }
set { SetProperty(StringNullDefaultValueProperty, value); }
}
#endregion
}
} | 35.44186 | 163 | 0.687664 | [
"MIT"
] | Eduardo-Micromust/csla | Source/Csla.test/PropertyInfo/PropertyInfoRoot.cs | 3,050 | C# |
using UnityEngine;
namespace UnityEngine.ProBuilder
{
/// <summary>
/// Vertex positions are sorted as integers to avoid floating point precision errors.
/// </summary>
struct IntVec3 : System.IEquatable<IntVec3>
{
public Vector3 value;
public float x { get { return value.x; } }
public float y { get { return value.y; } }
public float z { get { return value.z; } }
public IntVec3(Vector3 vector)
{
this.value = vector;
}
public override string ToString()
{
return string.Format("({0:F2}, {1:F2}, {2:F2})", x, y, z);
}
public static bool operator==(IntVec3 a, IntVec3 b)
{
return a.Equals(b);
}
public static bool operator!=(IntVec3 a, IntVec3 b)
{
return !(a == b);
}
public bool Equals(IntVec3 p)
{
return round(x) == round(p.x) &&
round(y) == round(p.y) &&
round(z) == round(p.z);
}
public bool Equals(Vector3 p)
{
return round(x) == round(p.x) &&
round(y) == round(p.y) &&
round(z) == round(p.z);
}
public override bool Equals(System.Object b)
{
return (b is IntVec3 && (this.Equals((IntVec3)b))) ||
(b is Vector3 && this.Equals((Vector3)b));
}
public override int GetHashCode()
{
return VectorHash.GetHashCode(value);
}
private static int round(float v)
{
return System.Convert.ToInt32(v * VectorHash.FltCompareResolution);
}
public static implicit operator Vector3(IntVec3 p)
{
return p.value;
}
public static implicit operator IntVec3(Vector3 p)
{
return new IntVec3(p);
}
}
}
| 25.051948 | 89 | 0.498186 | [
"MIT"
] | ASE-Blast/unity3dgames | Space Game/Library/PackageCache/[email protected]/Runtime/Core/IntVec3.cs | 1,929 | C# |
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Cynosura.Core.Data;
using Cynosura.Template.Core.Entities;
using Cynosura.Template.Core.FileStorage;
using Cynosura.Template.Core.Infrastructure;
using Cynosura.Template.Core.Requests.Files.Models;
namespace Cynosura.Template.Core.Requests.Files
{
public class DownloadFileHandler : IRequestHandler<DownloadFile, FileContentModel>
{
private readonly IEntityRepository<File> _fileRepository;
private readonly IFileStorage _fileStorage;
public DownloadFileHandler(IEntityRepository<File> fileRepository,
IFileStorage fileStorage)
{
_fileRepository = fileRepository;
_fileStorage = fileStorage;
}
public async Task<FileContentModel> Handle(DownloadFile request, CancellationToken cancellationToken)
{
var file = await _fileRepository.GetEntities()
.Include(e => e.Group)
.Where(e => e.Id == request.Id)
.FirstOrDefaultAsync();
byte[] content = null;
if (file.Group.Type == Enums.FileGroupType.Database)
{
content = file.Content;
}
else if (file.Group.Type == Enums.FileGroupType.Storage)
{
content = await _fileStorage.DownloadFileAsync(file.Url);
}
else
{
throw new NotSupportedException($"Group type {file.Group.Type} not supported");
}
return new FileContentModel
{
Name = file.Name,
ContentType = file.ContentType,
Content = content,
};
}
}
}
| 32.210526 | 109 | 0.617102 | [
"MIT"
] | CynosuraPlatform/Cynosura.Template | src/Cynosura.Template.Core/Requests/Files/DownloadFileHandler.cs | 1,838 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System.Text.Json;
using Azure.Core;
namespace Azure.AI.TextAnalytics.Models
{
internal partial class KeyPhraseLROTask : IUtf8JsonSerializable
{
void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
{
writer.WriteStartObject();
if (Optional.IsDefined(Parameters))
{
writer.WritePropertyName("parameters");
writer.WriteObjectValue(Parameters);
}
writer.WritePropertyName("kind");
writer.WriteStringValue(Kind.ToString());
if (Optional.IsDefined(TaskName))
{
writer.WritePropertyName("taskName");
writer.WriteStringValue(TaskName);
}
writer.WriteEndObject();
}
internal static KeyPhraseLROTask DeserializeKeyPhraseLROTask(JsonElement element)
{
Optional<KeyPhraseTaskParameters> parameters = default;
AnalyzeTextLROTaskKind kind = default;
Optional<string> taskName = default;
foreach (var property in element.EnumerateObject())
{
if (property.NameEquals("parameters"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
property.ThrowNonNullablePropertyIsNull();
continue;
}
parameters = KeyPhraseTaskParameters.DeserializeKeyPhraseTaskParameters(property.Value);
continue;
}
if (property.NameEquals("kind"))
{
kind = new AnalyzeTextLROTaskKind(property.Value.GetString());
continue;
}
if (property.NameEquals("taskName"))
{
taskName = property.Value.GetString();
continue;
}
}
return new KeyPhraseLROTask(taskName.Value, kind, parameters.Value);
}
}
}
| 33.907692 | 108 | 0.544011 | [
"MIT"
] | ChenTanyi/azure-sdk-for-net | sdk/textanalytics/Azure.AI.TextAnalytics/src/Generated/Models/KeyPhraseLROTask.Serialization.cs | 2,204 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Assets.Scripts.Environnement
{
public class Room {
public Vector2 gridPos;
public RoomType RoomType;
public bool doorTop, doorBot, doorLeft, doorRight;
public Room roomTop, roomBot, roomLeft, roomRight;
public MapSpriteSelector Mapper;
public Room(Vector2 _gridPos, RoomType _RoomType){
gridPos = _gridPos;
RoomType = _RoomType;
}
public override string ToString() {
return "Salle: Pos = "+gridPos+", roomTop="+(roomTop != null)+", roomBot="+(roomBot != null)+", roomLeft="+(roomLeft != null)+", roomRight="+(roomRight != null);
}
}
} | 28.166667 | 177 | 0.696746 | [
"Apache-2.0"
] | istic-student/roguelike | Assets/Scripts/Environnement/Room.cs | 678 | C# |
/*
MIT License
Copyright (c) 2019 Matthias Müller
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 MailKit;
using MailKit.Net.Imap;
using MailKit.Search;
using MailToDatabase.Contracts;
using MimeKit;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace MailToDatabase.Clients
{
public class GenericClient : IMailToDatabaseClient, IRetrievalClient
{
public string EmailAddress { get; }
public string Password { get; }
public string ServerURL { get; }
public ushort Port { get; }
public string OpenedMailFolder => _mailFolder?.Name;
protected const MessageSummaryItems MessageSummaryOptions = MessageSummaryItems.UniqueId
| MessageSummaryItems.Size
| MessageSummaryItems.Flags
//| MessageSummaryItems.BodyStructure
//| MessageSummaryItems.GMailLabels
//| MessageSummaryItems.GMailMessageId
//| MessageSummaryItems.InternalDate
//| MessageSummaryItems.PreviewText
| MessageSummaryItems.References
| MessageSummaryItems.Envelope;
protected readonly ImapClient _imapClient = new ImapClient();
protected IMailFolder _mailFolder;
protected string[] _mailFolders;
protected IList<UniqueId> _lastRetrievedUIds;
public int MailCountInFolder => _mailFolder?.Count ?? -1;
public GenericClient(Credentials credentials)
{
EmailAddress = credentials.EmailAddress;
ServerURL = credentials.ServerURL;
Password = credentials.Password;
Port = credentials.Port;
}
public GenericClient(string usernameOrEmailAddress,
string serverURL,
string password,
ushort port)
{
EmailAddress = usernameOrEmailAddress;
ServerURL = serverURL;
Password = password;
Port = port;
}
public virtual async Task<int> GetTotalMailCount()
{
_mailFolder = await AuthenticateAsync();
_mailFolder.Open(FolderAccess.ReadOnly);
return (await _mailFolder.SearchAsync(SearchQuery.All))?.Count ?? 0;
}
public virtual async Task<IList<string>> GetMailFoldersAsync(Action<Exception> errorHandeling = null)
{
try
{
if (!_imapClient.IsConnected)
{
await _imapClient.ConnectAsync(ServerURL, Port, true);
_imapClient.AuthenticationMechanisms.Remove("XOAUTH");
await _imapClient.AuthenticateAsync(EmailAddress, Password);
}
}
catch (Exception ex)
{
errorHandeling?.Invoke(ex);
}
var personal = _imapClient.GetFolder(_imapClient.PersonalNamespaces[0]);
var list = new List<string>();
await foreach (var folder in GetFolderRecursivelyAsync(personal))
{
list.Add(folder.Name);
}
return list;
}
protected virtual async IAsyncEnumerable<IMailFolder> GetFolderRecursivelyAsync(IMailFolder mailFolder)
{
foreach (var subFolder in await mailFolder.GetSubfoldersAsync(false, CancellationToken.None))
{
if ((await subFolder.GetSubfoldersAsync(false, CancellationToken.None)).Any())
{
await foreach (var folder in GetFolderRecursivelyAsync(subFolder))
{
yield return folder;
}
}
yield return subFolder;
}
}
public virtual async Task<IMailFolder> AuthenticateAsync(CancellationToken cancellationToken = default)
{
if (!_imapClient.IsConnected)
{
await _imapClient.ConnectAsync(ServerURL, Port, true);
_imapClient.AuthenticationMechanisms.Remove("XOAUTH");
await _imapClient.AuthenticateAsync(EmailAddress, Password);
}
if (_mailFolders == null)
{
_mailFolders = new[] { "inbox" };
}
var personal = _imapClient.GetFolder(_imapClient.PersonalNamespaces[0]);
await foreach (var folder in GetFolderRecursivelyAsync(personal))
{
if (_mailFolders.Contains(folder.Name.ToLower()))
{
return folder;
}
}
throw new MailFolderNotFoundException($"Mail folder(s) '{string.Join(", ", _mailFolders)}' not found.");
}
/// <summary>
/// Sets the mailfolder the IMAP client should be running its methods on.
/// Search will check each variant of the folder names passed in and set
/// the first that matches. Uses 'StringComparison.OrdinalIgnoreCase'.
/// </summary>
/// <param name="folderNames"></param>
public virtual void SetMailFolder(params string[] folderNames)
{
_mailFolders = folderNames.Select(x => x.ToLower()).ToArray();
}
public virtual async Task<IList<UniqueId>> GetUIds(ImapFilter filter = null)
{
_mailFolder = await AuthenticateAsync();
await _mailFolder.OpenAsync(FolderAccess.ReadOnly);
if (filter == null)
{
_lastRetrievedUIds = await _mailFolder.SearchAsync(new SearchQuery());
}
else
{
_lastRetrievedUIds = await _mailFolder.SearchAsync(filter.ToSearchQuery());
}
if (_lastRetrievedUIds == null)
{
_lastRetrievedUIds = new List<UniqueId>();
}
return _lastRetrievedUIds;
}
public virtual async Task<List<MimeMessageUId>> GetMessageUids(IList<UniqueId> uniqueIds)
{
_mailFolder = await AuthenticateAsync();
_mailFolder.Open(FolderAccess.ReadOnly);
var list = new List<MimeMessageUId>();
foreach (var uid in uniqueIds)
{
list.Add(new MimeMessageUId(await _mailFolder.GetMessageAsync(uid), uid));
}
return list;
}
public virtual async Task<MimeMessageUId> GetMessageUid(UniqueId uniqueId)
{
var mime = await _mailFolder.GetMessageAsync(uniqueId);
if (mime != null)
{
return new MimeMessageUId(mime, uniqueId);
}
return null;
}
public virtual async Task<MimeMessageUId> GetMessage(UniqueId uniqueId)
{
_mailFolder = await AuthenticateAsync();
await _mailFolder.OpenAsync(FolderAccess.ReadOnly);
return new MimeMessageUId(await _mailFolder.GetMessageAsync(uniqueId), uniqueId);
}
public virtual async Task<IList<IMessageSummary>> GetSummaries()
{
var inbox = await AuthenticateAsync();
await inbox.OpenAsync(FolderAccess.ReadOnly);
return await inbox.FetchAsync(0, -1, MessageSummaryOptions);
}
public virtual async Task<IList<IMessageSummary>> GetSummaries(IList<UniqueId> uids)
{
var inbox = await AuthenticateAsync();
await inbox.OpenAsync(FolderAccess.ReadOnly);
return await inbox.FetchAsync(uids, MessageSummaryOptions);
}
public virtual async Task<IList<IMessageSummary>> GetSummaries(ImapFilter filter, uint[] uidsToExclude = null)
{
var inbox = await AuthenticateAsync();
await inbox.OpenAsync(FolderAccess.ReadOnly);
_lastRetrievedUIds = await GetUIds(filter);
if (uidsToExclude?.Length > 0)
{
_lastRetrievedUIds = _lastRetrievedUIds.Where(x => !uidsToExclude.Contains(x.Id)).ToArray();
}
return await inbox.FetchAsync(_lastRetrievedUIds, MessageSummaryOptions);
}
public virtual async Task MarkAsRead(IList<UniqueId> uids)
{
if (_mailFolder == null)
{
_mailFolder = await AuthenticateAsync();
}
await _mailFolder.OpenAsync(FolderAccess.ReadWrite);
await _mailFolder.SetFlagsAsync(uids, MessageFlags.Seen, false);
}
public virtual async Task DeleteMessages(IList<UniqueId> uids)
{
if (_mailFolder == null)
{
_mailFolder = await AuthenticateAsync();
}
await _mailFolder.OpenAsync(FolderAccess.ReadWrite);
await _mailFolder.SetFlagsAsync(uids, MessageFlags.Deleted, false);
}
public virtual async Task DeleteMessages(ImapFilter imapFilter)
{
var uids = await GetUIds(imapFilter);
await DeleteMessages(uids);
}
public virtual async Task ExpungeMail()
{
if (_mailFolder == null)
{
_mailFolder = await AuthenticateAsync();
}
await _mailFolder.OpenAsync(FolderAccess.ReadWrite);
await _mailFolder.ExpungeAsync();
}
public virtual async Task<UniqueId?> AppendMessage(MimeMessage mimeMessage, bool asNotSeen = false)
{
var flags = asNotSeen ? MessageFlags.None : MessageFlags.Seen;
if (_mailFolder == null)
{
_mailFolder = await AuthenticateAsync();
}
await _mailFolder.OpenAsync(FolderAccess.ReadWrite);
return await _mailFolder.AppendAsync(mimeMessage);
}
#region IDisposable Support
private bool disposedValue = false; // To detect redundant calls
protected async virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
// TODO: dispose managed state (managed objects).
if (_mailFolder != null && _mailFolder.IsOpen)
{
await _mailFolder.CloseAsync();
}
if (_imapClient?.IsConnected == true)
{
await _imapClient.DisconnectAsync(true);
_imapClient.Dispose();
}
}
// TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
// TODO: set large fields to null.
_lastRetrievedUIds = null;
_mailFolder = null;
_mailFolders = null;
disposedValue = true;
}
}
public void Dispose()
{
Dispose(true);
}
#endregion
}
}
| 37.668675 | 118 | 0.568767 | [
"MIT"
] | penCsharpener/MailToDatabase | src/MailToDatabase/Clients/GenericClient.cs | 12,509 | C# |
using System;
using System.Collections;
using System.Globalization;
using System.Windows;
#if DESKTOP
using System.Windows.Data;
#elif MODERN
using Windows.UI.Xaml;
using Windows.UI.Xaml.Data;
#elif PHONE
using System.Windows.Data;
#endif
namespace Neptune.UI.Converters
{
public class NullToVisibilityConverter : IValueConverter
{
#if MODERN
public object Convert(object value, Type targetType, object parameter, string culture)
#else
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
#endif
{
var invert = false;
if (parameter != null)
{
Boolean.TryParse(parameter.ToString(), out invert);
}
if (value == null) return invert ? Visibility.Visible : Visibility.Collapsed;
if (value is string)
return string.IsNullOrWhiteSpace((string)value) || invert ? Visibility.Collapsed : Visibility.Visible;
if (value is IList)
{
bool empty = ((IList)value).Count == 0;
if (invert)
empty = !empty;
if (empty)
return Visibility.Collapsed;
else
return Visibility.Visible;
}
decimal number;
if (Decimal.TryParse(value.ToString(), out number))
{
if (!invert)
return number > 0 ? Visibility.Visible : Visibility.Collapsed;
else
return number > 0 ? Visibility.Collapsed : Visibility.Visible;
}
return invert ? Visibility.Collapsed : Visibility.Visible;
}
#if MODERN
public object ConvertBack(object value, Type targetType, object parameter, string culture)
#else
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
#endif
{
throw new NotImplementedException();
}
}
}
| 28.591549 | 118 | 0.58867 | [
"Apache-2.0"
] | NeonWiredX/meridian | Neptune/Trunk/Neptune.Desktop/Converters/NullToVisibilityConverter.cs | 2,032 | C# |
using IronPython.Runtime;
using IronPython.Runtime.Types;
using Microsoft.Scripting.Actions;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
namespace NFox.Pycad.Types
{
public abstract class ValueBase : TypeBase
{
protected ValueBase(string text, object value)
{
Name = text;
Value = value;
}
public dynamic Value { get; protected set; }
public virtual bool IsCallable { get { return false; } }
protected virtual void NewOverloads() { }
public List<string> _overloads;
public List<string> Overloads
{
get
{
if (_overloads == null)
NewOverloads();
return _overloads;
}
}
public virtual dynamic ClrType
{
get { return Engine.Instance.GetValue("clr").GetClrType(Engine.Instance.GetValue("type")(Value)); }
}
private const string NewStyleTypeName =
"IronPython.NewTypes.System.Object_1$1";
public static ValueBase GetValue(string name, object value, dynamic type = null)
{
if (type == null)
{
if (value == null)
return new None(name);
type = Engine.Instance.GetValue("type")(value);
}
//.Net数据类型
if (value is NamespaceTracker)
return new Namespace(name, value);
if (value is ReflectedEvent.BoundEvent)
return new Event(name, value);
//Python数据类型
if (value is PythonModule)
return new Module(name, value);
if (value is OldClass)
return new Class(name, value);
if (value is Method ||
value is PythonFunction ||
value is BuiltinFunction ||
value is BuiltinMethodDescriptor ||
value is ClassMethodDescriptor)
return new Function(name, value);
//类型
if (value is PythonType)
{
type = Engine.Instance.GetValue("clr").GetClrType(value);
if (type.IsEnum)
return new Enum(name, value);
else if (type.FullName == NewStyleTypeName)
return new Type(name, value);
else
return new NetType(name, value);
}
if (type is ReflectedProperty)
type = type.PropertyType;
if (type is ReflectedPropertyTracker)
type = type.DeclaringType;
if (type is PythonType || type is System.Type)
{
dynamic t = Engine.Instance.GetValue("clr").GetClrType(type);
//Python对象
if (value is OldInstance || t.FullName == NewStyleTypeName)
{
//设置__call__按函数处理
if (Engine.Instance.GetValue("callable")(value))
return new Function(name, value);
else
return new Variant(name, value);
}
return new NetVariant(name, value, type);
}
return new NetVariant(name, value);
}
public virtual bool HasItems { get { return false; } }
public virtual ValueBase GetItem(string key)
{
if (Marshal.IsComObject(Value))
return null;
try { return ValueBase.GetValue(key, Engine.Instance.GetValue("getattr")(Value, key)); }
catch { return null; }
}
public virtual IEnumerable<ValueTree> GetItems()
{
List lst = Engine.Instance.GetValue("clr").Dir(Value);
if (lst != null)
{
foreach (string key in lst)
{
dynamic obj = null;
try { obj = Engine.Instance.GetValue("getattr")(Value, key); }
catch { }
yield return new ValueTree(ValueBase.GetValue(key, obj));
}
}
}
public virtual string TypeName { get { return Engine.Instance.GetValue("type")(Value).__name__; } }
}
public class Variant : ValueBase
{
private static List<string> _basetypes =
new List<string>{
"int", "float", "bool", "tuple", "list", "dict", "set", "str"
};
public Variant(string name, object value) : base(name, value) { }
public override string Description { get { return Engine.Instance.GetStr(Value); } }
public override bool HasItems
{
get { return !_basetypes.Contains(TypeName); }
}
public override int Order
{
get { return 0; }
}
}
public class None : Variant
{
public override ValueBase GetItem(string key)
{
return null;
}
public None(string name) : base(name, null) { }
public override string Description { get { return "None"; } }
public override bool HasItems
{
get { return false; }
}
public override int Order
{
get { return 0; }
}
}
public class Function : ValueBase
{
public Function(string name, object value) : base(name, value) { }
public override bool IsCallable { get { return true; } }
protected override void NewOverloads()
{
var newfunc = Value;
_overloads = new List<string>();
if (Engine.Instance.GetValue("hasattr")(newfunc, "Overloads"))
{
foreach (var func in newfunc.Overloads.Functions)
_overloads.Add(func.__doc__);
}
else if (newfunc.__doc__ != null)
{
var ms = Regex.Matches(newfunc.__doc__, $"{Name}\\(.*?\\)(->.*?)*");
foreach (Match m in ms)
_overloads.Add(m.Value);
}
}
public override string Description
{
get
{
if (Engine.Instance.GetValue("hasattr")(Value, "__name__"))
return $"function {Engine.Instance.GetValue("getattr")(Value, "__name__")}";
return $"function {Value.__func__.__name__}";
}
}
public override int Order
{
get { return 1; }
}
}
public class Module : ValueBase
{
public Module(string name, object value) : base(name, value) { }
public override string Description { get { return $"module: {Value.__name__}"; } }
public override bool HasItems
{
get { return true; }
}
public override int Order
{
get { return 2; }
}
}
public class Class : ValueBase
{
public Class(string name, object value) : base(name, value) { }
public override string Description { get { return $"class {Value.__name__}"; } }
public override bool HasItems
{
get { return true; }
}
public override int Order
{
get { return 3; }
}
}
public class Type : ValueBase
{
public Type(string name, object value) : base(name, value) { }
public override bool IsCallable { get { return Engine.Instance.GetValue("callable")(Value.__new__); } }
protected override void NewOverloads()
{
var newfunc = Value.__new__;
_overloads = new List<string>();
if (Engine.Instance.GetValue("hasattr")(newfunc, "Overloads"))
{
foreach (var func in newfunc.Overloads.Functions)
_overloads.Add(func.__doc__);
}
else
{
_overloads.Add(newfunc.__doc__);
}
}
public override string Description
{
get
{
return $"type {Value.__name__}";
}
}
public override bool HasItems
{
get { return true; }
}
public override int Order
{
get { return 3; }
}
}
}
| 27.280645 | 111 | 0.501833 | [
"MIT"
] | qingliu2018/Pycad | src/NFox.Pycad.Runtime/Types/ValueBase.cs | 8,497 | C# |
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("AWSSDK.ElasticBeanstalk")]
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - AWS Elastic Beanstalk. AWS Elastic Beanstalk is an easy-to-use service for deploying and scaling web applications and services developed with Java, .NET, PHP, Node.js, Python, Ruby, Go, and Docker on familiar servers such as Apache, Nginx, Passenger, and IIS.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("Amazon Web Services SDK for .NET")]
[assembly: AssemblyCompany("Amazon.com, Inc")]
[assembly: AssemblyCopyright("Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.")]
[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)]
// 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("3.3")]
[assembly: AssemblyFileVersion("3.7.0.97")] | 50.28125 | 339 | 0.751398 | [
"Apache-2.0"
] | MDanialSaleem/aws-sdk-net | sdk/code-analysis/ServiceAnalysis/ElasticBeanstalk/Properties/AssemblyInfo.cs | 1,609 | C# |
namespace Nop.Core.Domain.Orders
{
/// <summary>
/// Represents an order average report line summary
/// </summary>
public partial class OrderAverageReportLineSummary
{
/// <summary>
/// Gets or sets the order status
/// </summary>
public OrderStatus OrderStatus { get; set; }
/// <summary>
/// Gets or sets the sum today total
/// </summary>
public decimal SumTodayOrders { get; set; }
/// <summary>
/// Gets or sets the today count
/// </summary>
public int CountTodayOrders { get; set; }
/// <summary>
/// Gets or sets the sum this week total
/// </summary>
public decimal SumThisWeekOrders { get; set; }
/// <summary>
/// Gets or sets the this week count
/// </summary>
public int CountThisWeekOrders { get; set; }
/// <summary>
/// Gets or sets the sum this month total
/// </summary>
public decimal SumThisMonthOrders { get; set; }
/// <summary>
/// Gets or sets the this month count
/// </summary>
public int CountThisMonthOrders { get; set; }
/// <summary>
/// Gets or sets the sum this year total
/// </summary>
public decimal SumThisYearOrders { get; set; }
/// <summary>
/// Gets or sets the this year count
/// </summary>
public int CountThisYearOrders { get; set; }
/// <summary>
/// Gets or sets the sum all time total
/// </summary>
public decimal SumAllTimeOrders { get; set; }
/// <summary>
/// Gets or sets the all time count
/// </summary>
public int CountAllTimeOrders { get; set; }
}
}
| 28.015625 | 55 | 0.532627 | [
"MIT"
] | ASP-WAF/FireWall | Samples/NopeCommerce/Libraries/Nop.Core/Domain/Orders/OrderAverageReportLineSummary.cs | 1,793 | C# |
namespace Marble.Infrastructure.Identity.Configurations
{
public class JwtConfig
{
/// <summary>
/// Who has issued the token
/// </summary>
public string Issuer { get; set; }
/// <summary>
/// Who is the token intended for
/// </summary>
public string Audience { get; set; }
public string SecureKey { get; set; }
/// <summary>
/// The token expiry time
/// </summary>
public int ExpiryInMinutes { get; set; }
}
} | 24.181818 | 55 | 0.530075 | [
"MIT"
] | abdurrahman/marble | src/Marble.Infrastructure.Identity/Configurations/JwtConfig.cs | 532 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\General\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
private static void Vector128BooleanAsUInt16()
{
bool succeeded = false;
try
{
Vector128<ushort> result = default(Vector128<bool>).AsUInt16();
}
catch (NotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector128BooleanAsUInt16: RunNotSupportedScenario failed to throw NotSupportedException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
}
| 36.255814 | 150 | 0.563823 | [
"MIT"
] | 2m0nd/runtime | src/tests/JIT/HardwareIntrinsics/General/NotSupported/Vector128BooleanAsUInt16.cs | 1,559 | 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 System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Microsoft Azure Powershell - DataFactoryV2 Manager")]
[assembly: AssemblyCompany(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyCompany)]
[assembly: AssemblyProduct(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyProduct)]
[assembly: AssemblyCopyright(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyCopyright)]
[assembly: ComVisible(false)]
[assembly: CLSCompliant(false)]
[assembly: Guid("5d024af0-81c9-44f0-b3b0-7080f103fb4d")]
[assembly: AssemblyVersion("1.8.2")]
[assembly: AssemblyFileVersion("1.8.2")]
#if !SIGN
[assembly: InternalsVisibleTo("Microsoft.Azure.PowerShell.Cmdlets.DataFactoryV2.Test")]
#endif
| 48.242424 | 104 | 0.697236 | [
"MIT"
] | Ceespino/azure-powershell | src/DataFactory/DataFactoryV2/Properties/AssemblyInfo.cs | 1,560 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.GoogleNative.Composer.V1Beta1.Inputs
{
/// <summary>
/// Configuration for resources used by Airflow schedulers.
/// </summary>
public sealed class SchedulerResourceArgs : Pulumi.ResourceArgs
{
/// <summary>
/// Optional. The number of schedulers.
/// </summary>
[Input("count")]
public Input<int>? Count { get; set; }
/// <summary>
/// Optional. CPU request and limit for a single Airflow scheduler replica.
/// </summary>
[Input("cpu")]
public Input<double>? Cpu { get; set; }
/// <summary>
/// Optional. Memory (GB) request and limit for a single Airflow scheduler replica.
/// </summary>
[Input("memoryGb")]
public Input<double>? MemoryGb { get; set; }
/// <summary>
/// Optional. Storage (GB) request and limit for a single Airflow scheduler replica.
/// </summary>
[Input("storageGb")]
public Input<double>? StorageGb { get; set; }
public SchedulerResourceArgs()
{
}
}
}
| 29.914894 | 92 | 0.604552 | [
"Apache-2.0"
] | AaronFriel/pulumi-google-native | sdk/dotnet/Composer/V1Beta1/Inputs/SchedulerResourceArgs.cs | 1,406 | C# |
using MantaMTA.Core.Enums;
using MantaMTA.Core.Events;
using NUnit.Framework;
namespace MantaMTA.Core.Tests
{
[TestFixture]
public class FeedbackLoopTests : TestFixtureBase
{
[Test]
public void Aol()
{
using (CreateTransactionScopeObject())
{
EmailProcessingDetails processingDetails = EventsManager.Instance.ProcessFeedbackLoop(FeedbackLoopEmails.AolAbuse);
Assert.AreEqual(EmailProcessingResult.SuccessAbuse, processingDetails.ProcessingResult);
}
}
[Test]
public void Hotmail()
{
using (CreateTransactionScopeObject())
{
EmailProcessingDetails processingDetails = EventsManager.Instance.ProcessFeedbackLoop(FeedbackLoopEmails.HotmailAbuse);
Assert.AreEqual(EmailProcessingResult.SuccessAbuse, processingDetails.ProcessingResult);
}
}
[Test]
public void Yahoo()
{
using (CreateTransactionScopeObject())
{
EmailProcessingDetails processingDetails = EventsManager.Instance.ProcessFeedbackLoop(FeedbackLoopEmails.YahooAbuse);
Assert.AreEqual(EmailProcessingResult.SuccessAbuse, processingDetails.ProcessingResult);
}
}
[Test]
public void Fastmail()
{
using (CreateTransactionScopeObject())
{
EmailProcessingDetails processingDetails = EventsManager.Instance.ProcessFeedbackLoop(FeedbackLoopEmails.FastMail);
Assert.AreEqual(EmailProcessingResult.SuccessAbuse, processingDetails.ProcessingResult);
}
}
}
}
| 28.686275 | 124 | 0.752563 | [
"MIT"
] | AidanDelaney/MantaMTA | MantaCoreTests/FeedbackLoopTests.cs | 1,465 | C# |
using System;
using System.Xml.Serialization;
namespace Niue.Alipay.Domain
{
/// <summary>
/// BizOrderQueryResponse Data Structure.
/// </summary>
[Serializable]
public class BizOrderQueryResponse : AopObject
{
/// <summary>
/// 操作动作。 CREATE_SHOP-创建门店, MODIFY_SHOP-修改门店, CREATE_ITEM-创建商品, MODIFY_ITEM-修改商品, EFFECTIVE_ITEM-上架商品, INVALID_ITEM-下架商品, RESUME_ITEM-暂停售卖商品, PAUSE_ITEM-恢复售卖商品
/// </summary>
[XmlElement("action")]
public string Action { get; set; }
/// <summary>
/// 操作模式:NORMAL-普通开店
/// </summary>
[XmlElement("action_mode")]
public string ActionMode { get; set; }
/// <summary>
/// 支付宝流水ID
/// </summary>
[XmlElement("apply_id")]
public string ApplyId { get; set; }
/// <summary>
/// 流水上下文信息,JSON格式。根据action不同对应的结构也不同,JSON字段与含义可参考各个接口的请求参数。
/// </summary>
[XmlElement("biz_context_info")]
public string BizContextInfo { get; set; }
/// <summary>
/// 业务主体ID。根据biz_type不同可能对应shop_id或item_id。 特别注意对于门店创建,当流水status=SUCCESS时,此字段才为shop_id,其他状态时为0或空。
/// </summary>
[XmlElement("biz_id")]
public string BizId { get; set; }
/// <summary>
/// 业务类型:SHOP-店铺,ITEM-商品
/// </summary>
[XmlElement("biz_type")]
public string BizType { get; set; }
/// <summary>
/// 创建时间
/// </summary>
[XmlElement("create_time")]
public string CreateTime { get; set; }
/// <summary>
/// 操作用户的支付账号id
/// </summary>
[XmlElement("op_id")]
public string OpId { get; set; }
/// <summary>
/// 注意:此字段并非外部商户请求时传入的request_id,暂时代表支付宝内部字段,请勿用。
/// </summary>
[XmlElement("request_id")]
public string RequestId { get; set; }
/// <summary>
/// 流水处理结果码 <a href="https://doc.open.alipay.com/doc2/detail.htm?spm=a219a.7629140.0.0.lL9hGI&treeId=78&articleId=103834&docType=1#s2">点此查看</a>
/// </summary>
[XmlElement("result_code")]
public string ResultCode { get; set; }
/// <summary>
/// 流水处理结果描述
/// </summary>
[XmlElement("result_desc")]
public string ResultDesc { get; set; }
/// <summary>
/// 流水状态:INIT-初始,PROCESS-处理中,SUCCESS-成功,FAIL-失败。
/// </summary>
[XmlElement("status")]
public string Status { get; set; }
/// <summary>
/// 流水子状态:WAIT_CERTIFY-等待认证,LICENSE_AUDITING-证照审核中,RISK_AUDITING-风控审核中,WAIT_SIGN-等待签约,FINISH-终结。
/// </summary>
[XmlElement("sub_status")]
public string SubStatus { get; set; }
/// <summary>
/// 更新时间
/// </summary>
[XmlElement("update_time")]
public string UpdateTime { get; set; }
}
}
| 29.793814 | 175 | 0.551903 | [
"MIT"
] | P79N6A/abp-ant-design-pro-vue | Niue.Alipay/Domain/BizOrderQueryResponse.cs | 3,452 | C# |
using Sharpen;
namespace java.nio
{
[Sharpen.NakedStub]
public sealed class ServerSocketChannelImpl
{
}
}
| 11.1 | 44 | 0.756757 | [
"Apache-2.0"
] | Conceptengineai/XobotOS | android/generated/java/nio/ServerSocketChannelImpl.cs | 111 | 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.Diagnostics;
using System.Net.Sockets;
using System.Text;
namespace System.Net
{
internal static class SocketAddressPal
{
public const int DataOffset = 0;
public readonly static int IPv6AddressSize = GetIPv6AddressSize();
public readonly static int IPv4AddressSize = GetIPv4AddressSize();
private static unsafe int GetIPv6AddressSize()
{
int ipv6AddressSize, unused;
Interop.Error err = Interop.Sys.GetIPSocketAddressSizes(&unused, &ipv6AddressSize);
Debug.Assert(err == Interop.Error.SUCCESS);
return ipv6AddressSize;
}
private static unsafe int GetIPv4AddressSize()
{
int ipv4AddressSize, unused;
Interop.Error err = Interop.Sys.GetIPSocketAddressSizes(&ipv4AddressSize, &unused);
Debug.Assert(err == Interop.Error.SUCCESS);
return ipv4AddressSize;
}
private static void ThrowOnFailure(Interop.Error err)
{
switch (err)
{
case Interop.Error.SUCCESS:
return;
case Interop.Error.EFAULT:
// The buffer was either null or too small.
throw new IndexOutOfRangeException();
case Interop.Error.EAFNOSUPPORT:
// There was no appropriate mapping from the platform address family.
throw new PlatformNotSupportedException();
default:
Debug.Fail("Unexpected failure in GetAddressFamily");
throw new PlatformNotSupportedException();
}
}
public static unsafe AddressFamily GetAddressFamily(byte[] buffer)
{
AddressFamily family;
Interop.Error err;
fixed (byte* rawAddress = buffer)
{
err = Interop.Sys.GetAddressFamily(rawAddress, buffer.Length, (int*)&family);
}
ThrowOnFailure(err);
return family;
}
public static unsafe void SetAddressFamily(byte[] buffer, AddressFamily family)
{
Interop.Error err;
fixed (byte* rawAddress = buffer)
{
err = Interop.Sys.SetAddressFamily(rawAddress, buffer.Length, (int)family);
}
ThrowOnFailure(err);
}
public static unsafe ushort GetPort(byte[] buffer)
{
ushort port;
Interop.Error err;
fixed (byte* rawAddress = buffer)
{
err = Interop.Sys.GetPort(rawAddress, buffer.Length, &port);
}
ThrowOnFailure(err);
return port;
}
public static unsafe void SetPort(byte[] buffer, ushort port)
{
Interop.Error err;
fixed (byte* rawAddress = buffer)
{
err = Interop.Sys.SetPort(rawAddress, buffer.Length, port);
}
ThrowOnFailure(err);
}
public static unsafe uint GetIPv4Address(byte[] buffer)
{
uint ipAddress;
Interop.Error err;
fixed (byte* rawAddress = buffer)
{
err = Interop.Sys.GetIPv4Address(rawAddress, buffer.Length, &ipAddress);
}
ThrowOnFailure(err);
return ipAddress;
}
public static unsafe void GetIPv6Address(byte[] buffer, byte[] address, out uint scope)
{
uint localScope;
Interop.Error err;
fixed (byte* rawAddress = buffer)
fixed (byte* ipAddress = address)
{
err = Interop.Sys.GetIPv6Address(rawAddress, buffer.Length, ipAddress, address.Length, &localScope);
}
ThrowOnFailure(err);
scope = localScope;
}
public static unsafe void SetIPv4Address(byte[] buffer, uint address)
{
Interop.Error err;
fixed (byte* rawAddress = buffer)
{
err = Interop.Sys.SetIPv4Address(rawAddress, buffer.Length, address);
}
ThrowOnFailure(err);
}
public static unsafe void SetIPv4Address(byte[] buffer, byte* address)
{
uint addr = (uint)System.Runtime.InteropServices.Marshal.ReadInt32((IntPtr)address);
SetIPv4Address(buffer, addr);
}
public static unsafe void SetIPv6Address(byte[] buffer, byte[] address, uint scope)
{
fixed (byte* rawInput = address)
{
SetIPv6Address(buffer, rawInput, address.Length, scope);
}
}
public static unsafe void SetIPv6Address(byte[] buffer, byte* address, int addressLength, uint scope)
{
Interop.Error err;
fixed (byte* rawAddress = buffer)
{
err = Interop.Sys.SetIPv6Address(rawAddress, buffer.Length, address, addressLength, scope);
}
ThrowOnFailure(err);
}
}
}
| 31.815476 | 116 | 0.559775 | [
"MIT"
] | er0dr1guez/corefx | src/Common/src/System/Net/SocketAddressPal.Unix.cs | 5,345 | C# |
//-----------------------------------------------------------------------
// <copyright file="RemoteActorRefProvider.cs" company="Akka.NET Project">
// Copyright (C) 2009-2016 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Akka.Actor;
using Akka.Actor.Internal;
using Akka.Configuration;
using Akka.Dispatch;
using Akka.Dispatch.SysMsg;
using Akka.Event;
using Akka.Remote.Configuration;
using Akka.Util.Internal;
namespace Akka.Remote
{
/// <summary>
/// INTERNAL API
/// </summary>
public class RemoteActorRefProvider : IActorRefProvider
{
private readonly ILoggingAdapter _log;
/// <summary>
/// TBD
/// </summary>
/// <param name="systemName">TBD</param>
/// <param name="settings">TBD</param>
/// <param name="eventStream">TBD</param>
public RemoteActorRefProvider(string systemName, Settings settings, EventStream eventStream)
{
settings.InjectTopLevelFallback(RemoteConfigFactory.Default());
var remoteDeployer = new RemoteDeployer(settings);
Func<ActorPath, IInternalActorRef> deadLettersFactory = path => new RemoteDeadLetterActorRef(this, path, eventStream);
_local = new LocalActorRefProvider(systemName, settings, eventStream, remoteDeployer, deadLettersFactory);
RemoteSettings = new RemoteSettings(settings.Config);
Deployer = remoteDeployer;
_log = _local.Log;
}
private readonly LocalActorRefProvider _local;
private volatile Internals _internals;
private ActorSystemImpl _system;
private Internals RemoteInternals
{
get { return _internals ?? (_internals = CreateInternals()); }
}
private Internals CreateInternals()
{
var internals =
new Internals(new Remoting(_system, this), _system.Serialization,
new RemoteSystemDaemon(_system, RootPath / "remote", RootGuardian, _remotingTerminator, _log));
_local.RegisterExtraName("remote", internals.RemoteDaemon);
return internals;
}
/// <summary>
/// TBD
/// </summary>
public IInternalActorRef RemoteDaemon { get { return RemoteInternals.RemoteDaemon; } }
/// <summary>
/// TBD
/// </summary>
public RemoteTransport Transport { get { return RemoteInternals.Transport; } }
/// <summary>
/// TBD
/// </summary>
internal RemoteSettings RemoteSettings { get; private set; }
/* these are only available after Init() is called */
/// <summary>
/// TBD
/// </summary>
public ActorPath RootPath
{
get { return _local.RootPath; }
}
/// <summary>
/// TBD
/// </summary>
public IInternalActorRef RootGuardian { get { return _local.RootGuardian; } }
/// <summary>
/// TBD
/// </summary>
public LocalActorRef Guardian { get { return _local.Guardian; } }
/// <summary>
/// TBD
/// </summary>
public LocalActorRef SystemGuardian { get { return _local.SystemGuardian; } }
/// <summary>
/// TBD
/// </summary>
public IInternalActorRef TempContainer { get { return _local.TempContainer; } }
/// <summary>
/// TBD
/// </summary>
public IActorRef DeadLetters { get { return _local.DeadLetters; } }
/// <summary>
/// TBD
/// </summary>
public Deployer Deployer { get; protected set; }
/// <summary>
/// TBD
/// </summary>
public Address DefaultAddress { get { return Transport.DefaultAddress; } }
/// <summary>
/// TBD
/// </summary>
public Settings Settings { get { return _local.Settings; } }
/// <summary>
/// TBD
/// </summary>
public Task TerminationTask { get { return _local.TerminationTask; } }
private IInternalActorRef InternalDeadLetters { get { return (IInternalActorRef)_local.DeadLetters; } }
/// <summary>
/// TBD
/// </summary>
/// <returns>TBD</returns>
public ActorPath TempPath()
{
return _local.TempPath();
}
/// <summary>
/// TBD
/// </summary>
/// <param name="actorRef">TBD</param>
/// <param name="path">TBD</param>
public void RegisterTempActor(IInternalActorRef actorRef, ActorPath path)
{
_local.RegisterTempActor(actorRef, path);
}
/// <summary>
/// TBD
/// </summary>
/// <param name="path">TBD</param>
public void UnregisterTempActor(ActorPath path)
{
_local.UnregisterTempActor(path);
}
private volatile IActorRef _remotingTerminator;
private volatile IActorRef _remoteWatcher;
/// <summary>
/// TBD
/// </summary>
internal IActorRef RemoteWatcher => _remoteWatcher;
private volatile IActorRef _remoteDeploymentWatcher;
/// <summary>
/// TBD
/// </summary>
/// <param name="system">TBD</param>
public virtual void Init(ActorSystemImpl system)
{
_system = system;
_local.Init(system);
_remotingTerminator =
_system.SystemActorOf(
RemoteSettings.ConfigureDispatcher(Props.Create(() => new RemotingTerminator(_local.SystemGuardian))),
"remoting-terminator");
_remotingTerminator.Tell(RemoteInternals);
Transport.Start();
_remoteWatcher = CreateRemoteWatcher(system);
_remoteDeploymentWatcher = CreateRemoteDeploymentWatcher(system);
}
/// <summary>
/// TBD
/// </summary>
/// <param name="system">TBD</param>
/// <returns>TBD</returns>
protected virtual IActorRef CreateRemoteWatcher(ActorSystemImpl system)
{
var failureDetector = CreateRemoteWatcherFailureDetector(system);
return system.SystemActorOf(RemoteSettings.ConfigureDispatcher(
Akka.Remote.RemoteWatcher.Props(
failureDetector,
RemoteSettings.WatchHeartBeatInterval,
RemoteSettings.WatchUnreachableReaperInterval,
RemoteSettings.WatchHeartbeatExpectedResponseAfter)), "remote-watcher");
}
/// <summary>
/// TBD
/// </summary>
/// <param name="system">TBD</param>
/// <returns>TBD</returns>
protected virtual IActorRef CreateRemoteDeploymentWatcher(ActorSystemImpl system)
{
return system.SystemActorOf(RemoteSettings.ConfigureDispatcher(Props.Create<RemoteDeploymentWatcher>()),
"remote-deployment-watcher");
}
/// <summary>
/// TBD
/// </summary>
/// <param name="system">TBD</param>
/// <returns>TBD</returns>
protected DefaultFailureDetectorRegistry<Address> CreateRemoteWatcherFailureDetector(ActorSystem system)
{
return new DefaultFailureDetectorRegistry<Address>(() =>
FailureDetectorLoader.Load(RemoteSettings.WatchFailureDetectorImplementationClass,
RemoteSettings.WatchFailureDetectorConfig, _system));
}
/// <summary>
/// TBD
/// </summary>
/// <param name="system">TBD</param>
/// <param name="props">TBD</param>
/// <param name="supervisor">TBD</param>
/// <param name="path">TBD</param>
/// <param name="systemService">TBD</param>
/// <param name="deploy">TBD</param>
/// <param name="lookupDeploy">TBD</param>
/// <param name="async">TBD</param>
/// <exception cref="ActorInitializationException">TBD</exception>
/// <exception cref="ConfigurationException">TBD</exception>
/// <returns>TBD</returns>
public IInternalActorRef ActorOf(ActorSystemImpl system, Props props, IInternalActorRef supervisor, ActorPath path, bool systemService, Deploy deploy, bool lookupDeploy, bool async)
{
if (systemService) return LocalActorOf(system, props, supervisor, path, true, deploy, lookupDeploy, async);
/*
* This needs to deal with "mangled" paths, which are created by remote
* deployment, also in this method. The scheme is the following:
*
* Whenever a remote deployment is found, create a path on that remote
* address below "remote", including the current system’s identification
* as "sys@host:port" (typically; it will use whatever the remote
* transport uses). This means that on a path up an actor tree each node
* change introduces one layer or "remote/scheme/sys@host:port/" within the URI.
*
* Example:
*
* akka.tcp://sys@home:1234/remote/akka/sys@remote:6667/remote/akka/sys@other:3333/user/a/b/c
*
* means that the logical parent originates from "akka.tcp://sys@other:3333" with
* one child (may be "a" or "b") being deployed on "akka.tcp://sys@remote:6667" and
* finally either "b" or "c" being created on "akka.tcp://sys@home:1234", where
* this whole thing actually resides. Thus, the logical path is
* "/user/a/b/c" and the physical path contains all remote placement
* information.
*
* Deployments are always looked up using the logical path, which is the
* purpose of the lookupRemotes internal method.
*/
var elements = path.Elements;
Deploy configDeploy = null;
if (lookupDeploy)
{
if (elements.Head().Equals("user")) configDeploy = Deployer.Lookup(elements.Drop(1));
else if (elements.Head().Equals("remote")) configDeploy = LookUpRemotes(elements);
}
//merge all of the fallbacks together
var deployment = new List<Deploy>() { deploy, configDeploy }.Where(x => x != null).Aggregate(Deploy.None, (deploy1, deploy2) => deploy2.WithFallback(deploy1));
var propsDeploy = new List<Deploy>() { props.Deploy, deployment }.Where(x => x != null)
.Aggregate(Deploy.None, (deploy1, deploy2) => deploy2.WithFallback(deploy1));
//match for remote scope
if (propsDeploy.Scope is RemoteScope)
{
var addr = propsDeploy.Scope.AsInstanceOf<RemoteScope>().Address;
//Even if this actor is in RemoteScope, it might still be a local address
if (HasAddress(addr))
{
return LocalActorOf(system, props, supervisor, path, false, deployment, false, async);
}
//check for correct scope configuration
if (props.Deploy.Scope is LocalScope)
{
throw new ConfigurationException(
string.Format("configuration requested remote deployment for local-only Props at {0}", path));
}
try
{
try
{
// for consistency we check configuration of dispatcher and mailbox locally
var dispatcher = _system.Dispatchers.Lookup(props.Dispatcher);
var mailboxType = _system.Mailboxes.GetMailboxType(props, dispatcher.Configurator.Config);
}
catch (Exception ex)
{
throw new ConfigurationException(
string.Format(
"Configuration problem while creating {0} with dispatcher [{1}] and mailbox [{2}]", path,
props.Dispatcher, props.Mailbox), ex);
}
var localAddress = Transport.LocalAddressForRemote(addr);
var rpath = (new RootActorPath(addr) / "remote" / localAddress.Protocol / localAddress.HostPort() /
path.Elements.ToArray()).
WithUid(path.Uid);
var remoteRef = new RemoteActorRef(Transport, localAddress, rpath, supervisor, props, deployment);
return remoteRef;
}
catch (Exception ex)
{
throw new ActorInitializationException(string.Format("Remote deployment failed for [{0}]", path), ex);
}
}
else
{
return LocalActorOf(system, props, supervisor, path, false, deployment, false, async);
}
}
/// <summary>
/// Looks up local overrides for remote deployments
/// </summary>
/// <param name="p"></param>
/// <returns></returns>
private Deploy LookUpRemotes(IEnumerable<string> p)
{
if (p == null || !p.Any()) return Deploy.None;
if (p.Head().Equals("remote")) return LookUpRemotes(p.Drop(3));
if (p.Head().Equals("user")) return Deployer.Lookup(p.Drop(1));
return Deploy.None;
}
private bool HasAddress(Address address)
{
return address == _local.RootPath.Address || address == RootPath.Address || Transport.Addresses.Any(a => a == address);
}
/// <summary>
/// TBD
/// </summary>
/// <param name="address">TBD</param>
/// <returns>TBD</returns>
public IActorRef RootGuardianAt(Address address)
{
if (HasAddress(address))
{
return RootGuardian;
}
return new RemoteActorRef(
Transport,
Transport.LocalAddressForRemote(address),
new RootActorPath(address),
ActorRefs.Nobody,
Props.None,
Deploy.None);
}
private IInternalActorRef LocalActorOf(ActorSystemImpl system, Props props, IInternalActorRef supervisor,
ActorPath path, bool systemService, Deploy deploy, bool lookupDeploy, bool async)
{
return _local.ActorOf(system, props, supervisor, path, systemService, deploy, lookupDeploy, async);
}
/// <summary>
/// INTERNAL API.
///
/// Called in deserialization of incoming remote messages where the correct local address is known.
/// </summary>
/// <param name="path">TBD</param>
/// <param name="localAddress">TBD</param>
/// <returns>TBD</returns>
internal IInternalActorRef ResolveActorRefWithLocalAddress(string path, Address localAddress)
{
ActorPath actorPath;
if (ActorPath.TryParse(path, out actorPath))
{
//the actor's local address was already included in the ActorPath
if (HasAddress(actorPath.Address))
{
// HACK: needed to make ActorSelections work
if (actorPath.ToStringWithoutAddress().Equals("/"))
return RootGuardian;
return _local.ResolveActorRef(RootGuardian, actorPath.ElementsWithUid);
}
return new RemoteActorRef(Transport, localAddress, new RootActorPath(actorPath.Address) / actorPath.ElementsWithUid, ActorRefs.Nobody, Props.None, Deploy.None);
}
_log.Debug("resolve of unknown path [{0}] failed", path);
return InternalDeadLetters;
}
/// <summary>
/// TBD
/// </summary>
/// <param name="path">TBD</param>
/// <returns>TBD</returns>
public IActorRef ResolveActorRef(string path)
{
if (path == String.Empty)
return ActorRefs.NoSender;
ActorPath actorPath;
if (ActorPath.TryParse(path, out actorPath))
return ResolveActorRef(actorPath);
_log.Debug("resolve of unknown path [{0}] failed", path);
return DeadLetters;
}
/// <summary>
/// TBD
/// </summary>
/// <param name="actorPath">TBD</param>
/// <returns>TBD</returns>
public IActorRef ResolveActorRef(ActorPath actorPath)
{
if (HasAddress(actorPath.Address))
{
return _local.ResolveActorRef(RootGuardian, actorPath.ElementsWithUid);
}
try
{
return new RemoteActorRef(Transport,
Transport.LocalAddressForRemote(actorPath.Address),
actorPath,
ActorRefs.Nobody,
Props.None,
Deploy.None);
}
catch (Exception ex)
{
_log.Warning("Error while resolving address [{0}] due to [{1}]", actorPath.Address, ex.Message);
return new EmptyLocalActorRef(this, RootPath, _local.EventStream);
}
}
/// <summary>
/// TBD
/// </summary>
/// <param name="address">TBD</param>
/// <returns>TBD</returns>
public Address GetExternalAddressFor(Address address)
{
if (HasAddress(address)) { return _local.RootPath.Address; }
if (!string.IsNullOrEmpty(address.Host) && address.Port.HasValue)
{
try
{
return Transport.LocalAddressForRemote(address);
}
catch
{
return null;
}
}
return null;
}
/// <summary>
/// TBD
/// </summary>
/// <param name="actor">TBD</param>
/// <param name="props">TBD</param>
/// <param name="deploy">TBD</param>
/// <param name="supervisor">TBD</param>
public void UseActorOnNode(RemoteActorRef actor, Props props, Deploy deploy, IInternalActorRef supervisor)
{
_log.Debug("[{0}] Instantiating Remote Actor [{1}]", RootPath, actor.Path);
IActorRef remoteNode = ResolveActorRef(new RootActorPath(actor.Path.Address) / "remote");
remoteNode.Tell(new DaemonMsgCreate(props, deploy, actor.Path.ToSerializationFormat(), supervisor));
_remoteDeploymentWatcher.Tell(new RemoteDeploymentWatcher.WatchRemote(actor, supervisor));
}
/// <summary>
/// Marks a remote system as out of sync and prevents reconnects until the quarantine timeout elapses.
/// </summary>
/// <param name="address">Address of the remote system to be quarantined</param>
/// <param name="uid">UID of the remote system, if the uid is not defined it will not be a strong quarantine but
/// the current endpoint writer will be stopped (dropping system messages) and the address will be gated
/// </param>
public void Quarantine(Address address, int? uid)
{
Transport.Quarantine(address, uid);
}
#region Internals
/// <summary>
/// All of the private internals used by <see cref="RemoteActorRefProvider"/>, namely its transport
/// registry, remote serializers, and the <see cref="RemoteDaemon"/> instance.
/// </summary>
class Internals : INoSerializationVerificationNeeded
{
/// <summary>
/// TBD
/// </summary>
/// <param name="transport">TBD</param>
/// <param name="serialization">TBD</param>
/// <param name="remoteDaemon">TBD</param>
public Internals(RemoteTransport transport, Akka.Serialization.Serialization serialization, IInternalActorRef remoteDaemon)
{
Transport = transport;
Serialization = serialization;
RemoteDaemon = remoteDaemon;
}
/// <summary>
/// TBD
/// </summary>
public RemoteTransport Transport { get; private set; }
/// <summary>
/// TBD
/// </summary>
public Akka.Serialization.Serialization Serialization { get; private set; }
/// <summary>
/// TBD
/// </summary>
public IInternalActorRef RemoteDaemon { get; private set; }
}
#endregion
#region RemotingTerminator
/// <summary>
/// Describes the FSM states of the <see cref="RemotingTerminator"/>
/// </summary>
enum TerminatorState
{
/// <summary>
/// TBD
/// </summary>
Uninitialized,
/// <summary>
/// TBD
/// </summary>
Idle,
/// <summary>
/// TBD
/// </summary>
WaitDaemonShutdown,
/// <summary>
/// TBD
/// </summary>
WaitTransportShutdown,
/// <summary>
/// TBD
/// </summary>
Finished
}
/// <summary>
/// Responsible for shutting down the <see cref="RemoteDaemon"/> and all transports
/// when the <see cref="ActorSystem"/> is being shutdown.
/// </summary>
private class RemotingTerminator : FSM<TerminatorState, Internals>, IRequiresMessageQueue<IUnboundedMessageQueueSemantics>
{
private readonly IActorRef _systemGuardian;
private readonly ILoggingAdapter _log;
public RemotingTerminator(IActorRef systemGuardian)
{
_systemGuardian = systemGuardian;
_log = Context.GetLogger();
InitFSM();
}
private void InitFSM()
{
When(TerminatorState.Uninitialized, @event =>
{
var internals = @event.FsmEvent as Internals;
if (internals != null)
{
_systemGuardian.Tell(RegisterTerminationHook.Instance);
return GoTo(TerminatorState.Idle).Using(internals);
}
return null;
});
When(TerminatorState.Idle, @event =>
{
if (@event.StateData != null && @event.FsmEvent is TerminationHook)
{
_log.Info("Shutting down remote daemon.");
@event.StateData.RemoteDaemon.Tell(TerminationHook.Instance);
return GoTo(TerminatorState.WaitDaemonShutdown);
}
return null;
});
// TODO: state timeout
When(TerminatorState.WaitDaemonShutdown, @event =>
{
if (@event.StateData != null && @event.FsmEvent is TerminationHookDone)
{
_log.Info("Remote daemon shut down; proceeding with flushing remote transports.");
@event.StateData.Transport.Shutdown()
.ContinueWith(t => TransportShutdown.Instance,
TaskContinuationOptions.ExecuteSynchronously)
.PipeTo(Self);
return GoTo(TerminatorState.WaitTransportShutdown);
}
return null;
});
When(TerminatorState.WaitTransportShutdown, @event =>
{
_log.Info("Remoting shut down.");
_systemGuardian.Tell(TerminationHookDone.Instance);
return Stop();
});
StartWith(TerminatorState.Uninitialized, null);
}
public sealed class TransportShutdown
{
private TransportShutdown() { }
private static readonly TransportShutdown _instance = new TransportShutdown();
public static TransportShutdown Instance
{
get
{
return _instance;
}
}
public override string ToString()
{
return "<TransportShutdown>";
}
}
}
#endregion
private class RemoteDeadLetterActorRef : DeadLetterActorRef
{
public RemoteDeadLetterActorRef(IActorRefProvider provider, ActorPath actorPath, EventStream eventStream)
: base(provider, actorPath, eventStream)
{
}
protected override void TellInternal(object message, IActorRef sender)
{
var send = message as EndpointManager.Send;
var deadLetter = message as DeadLetter;
if (send != null)
{
if (send.Seq == null)
{
base.TellInternal(send.Message, send.SenderOption ?? ActorRefs.NoSender);
}
}
else if (deadLetter?.Message is EndpointManager.Send)
{
var deadSend = (EndpointManager.Send)deadLetter.Message;
if (deadSend.Seq == null)
{
base.TellInternal(deadSend.Message, deadSend.SenderOption ?? ActorRefs.NoSender);
}
}
else
{
base.TellInternal(message, sender);
}
}
}
}
}
| 38.142651 | 189 | 0.537343 | [
"Apache-2.0"
] | corefan/akka.net | src/core/Akka.Remote/RemoteActorRefProvider.cs | 26,475 | C# |
using System;
using Survivor.Models.Enums;
namespace Survivor.Models
{
using static Common.ExceptionMessages;
public class Item
{
private readonly string name;
private readonly double weight;
public Item(string name, double weight, Category category)
{
this.Name = name;
this.Weight = weight;
this.Category = category;
}
public string Name
{
get => this.name;
private init
{
if (string.IsNullOrWhiteSpace(value))
{
throw new ArgumentException(InvalidNameExceptionMsg);
}
this.name = value;
}
}
public double Weight
{
get => this.weight;
private init
{
if (value <= 0.0)
{
throw new ArgumentException(InvalidWeightExceptionMsg);
}
this.weight = value;
}
}
public Category Category { get; }
public override string ToString()
=> $"{this.Name} ({this.Weight} kg.) - {this.Category}";
}
} | 23.150943 | 75 | 0.477588 | [
"MIT"
] | AtiVassileva/Survivor | Survivor.Models/Item.cs | 1,229 | C# |
using Abp.Runtime.Validation;
using HC.WeChat.Dto;
using HC.WeChat.DemandForecasts;
using System;
namespace HC.WeChat.DemandForecasts.Dtos
{
public class GetDemandForecastsInput : PagedSortedAndFilteredInputDto, IShouldNormalize
{
public Guid UserId { get; set; }
public Guid DemandForecastId { get; set; }
/// <summary>
/// 正常化排序使用
/// </summary>
public void Normalize()
{
if (string.IsNullOrEmpty(Sorting))
{
Sorting = "Id";
}
}
}
}
| 21.769231 | 91 | 0.577739 | [
"MIT"
] | DonaldTdz/GAWeChat | aspnet-core/src/HC.WeChat.Application/DemandForecasts/Dtos/GetDemandForecastsInput.cs | 580 | C# |
//===-----------------------------------------------------------------------==//
//
// Lockpwn - blazing fast symbolic analysis for concurrent Boogie programs
//
// Copyright (c) 2015 Pantazis Deligiannis ([email protected])
//
// This file is distributed under the MIT License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
using System;
using Microsoft.Boogie;
namespace Lockpwn
{
internal static class Utilities
{
/// <summary>
/// Checks if the given function should not be accessed.
/// </summary>
/// <param name="funcName">Function name</param>
/// <returns>Boolean value</returns>
internal static bool ShouldNotAccessFunction(string funcName)
{
if (funcName.StartsWith("$memcpy") || funcName.StartsWith("$memcpy_fromio") ||
funcName.StartsWith("$memset") ||
funcName.StartsWith("$malloc") || funcName.StartsWith("$alloc") ||
funcName.StartsWith("$free") ||
funcName.Equals("pthread_mutex_lock") ||
funcName.Equals("pthread_mutex_unlock"))
return true;
return false;
}
/// <summary>
/// These functions should be skipped from the analysis.
/// </summary>
/// <param name="funcName">Function name</param>
/// <returns>Boolean value</returns>
internal static bool ShouldSkipFromAnalysis(string funcName)
{
if (funcName.Equals("$initialize") ||
funcName.StartsWith("__SMACK_static_init") ||
funcName.StartsWith("__SMACK_init_func_memory_model") ||
funcName.StartsWith("__SMACK_init_func_corral_primitives") ||
funcName.StartsWith("__SMACK_init_func_thread") ||
funcName.StartsWith("boogie_si_record_") ||
funcName.StartsWith("$malloc") || funcName.StartsWith("$alloc") ||
funcName.StartsWith("$free") ||
funcName.Contains("pthread_mutex_init") ||
funcName.Contains("pthread_create") ||
funcName.Contains("pthread_join") ||
funcName.Contains("pthread_cond_init") ||
funcName.Contains("pthread_cond_wait") ||
funcName.Contains("pthread_mutex_destroy") ||
funcName.Contains("pthread_exit") ||
funcName.Contains("pthread_mutexattr_init") ||
funcName.Contains("pthread_mutexattr_settype") ||
funcName.Contains("pthread_self") ||
funcName.Contains("corral_atomic_begin") ||
funcName.Contains("corral_atomic_end") ||
funcName.Contains("corral_getThreadID") ||
funcName.Contains("__call_wrapper") ||
funcName.Contains("__SMACK_nondet") ||
funcName.Contains("__SMACK_dummy") ||
funcName.Contains("__VERIFIER_assert") ||
funcName.Contains("__VERIFIER_assume") ||
funcName.Contains("__VERIFIER_error") ||
funcName.Contains("__VERIFIER_nondet_int"))
return true;
return false;
}
/// <summary>
/// True if it is a PThread function
/// </summary>
/// <param name="funcName">Function name</param>
/// <returns>Boolean value</returns>
internal static bool IsPThreadFunction(string funcName)
{
if (funcName.Contains("pthread_mutex_init") ||
funcName.Contains("pthread_mutex_lock") ||
funcName.Contains("pthread_mutex_unlock") ||
funcName.Contains("pthread_create") ||
funcName.Contains("pthread_join") ||
funcName.Contains("pthread_cond_init") ||
funcName.Contains("pthread_cond_wait") ||
funcName.Contains("pthread_mutex_destroy") ||
funcName.Contains("pthread_exit") ||
funcName.Contains("pthread_mutexattr_init") ||
funcName.Contains("pthread_mutexattr_settype") ||
funcName.Contains("pthread_self") ||
funcName.Contains("__call_wrapper"))
return true;
return false;
}
}
}
| 38.48 | 84 | 0.627339 | [
"MIT"
] | pdeligia/lockpwn | Source/Driver/Utilities/Utilities.cs | 3,850 | C# |
// <copyright file="AssemblyInfo.cs">
// Copyright (c) 2019 by Adam Hellberg.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
// </copyright>
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("Cshrix.Tests")]
[assembly: InternalsVisibleTo("Cshrix.FSharp.Tests")]
| 34.538462 | 72 | 0.719376 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | Sharparam/cshrix-bot | src/Cshrix/Properties/AssemblyInfo.cs | 449 | C# |
using System;
using System.Text.RegularExpressions;
public class MatchPhoneNumber
{
public static void Main()
{
var pattern = @"\+359(\s|-)2\1\d{3}\1\d{4}";
var regex = new Regex(pattern);
var phoneNumbers = regex.Matches(Console.ReadLine());
var isFirst = true;
foreach (var number in phoneNumbers)
{
if (isFirst)
{
Console.Write(number);
isFirst = false;
continue;
}
Console.Write($", {number}");
}
Console.WriteLine();
}
}
| 23.115385 | 61 | 0.502496 | [
"MIT"
] | spzvtbg/02-Tech-modul | Fundamental task solutions/19. 0. Regular Expressions (RegEx) - Lab/02. Match Phone Number/MatchPhoneNumber.cs | 603 | C# |
using Sanatana.ErrorHandling;
using Sanatana.Permissions.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sanatana.Permissions.DAL
{
public interface IUserRoleQueries<TUserKey, TKey>
where TUserKey : struct
where TKey : struct
{
Task Create(List<UserRole<TUserKey, TKey>> roles);
Task<List<UserRole<TUserKey, TKey>>> Select();
Task<List<UserRole<TUserKey, TKey>>> Select(List<TUserKey> userIds);
Task Update(List<UserRole<TUserKey, TKey>> userRoles);
Task Delete(List<UserRole<TUserKey, TKey>> userRoles);
Task Delete(List<TKey> roleIds);
Task Delete(List<TUserKey> userIds);
}
}
| 31.375 | 76 | 0.699867 | [
"MIT"
] | RodionKulin/Sanatana.Permissions | Sanatana.Permissions/DAL/IUserRoleQueries.cs | 755 | C# |
#region
using System.Web.Optimization;
using Sitecore;
using Sitecore.Pipelines;
#endregion
namespace Projects.Reboot.Core.MVC
{
public class RegisterBundles
{
[UsedImplicitly]
public virtual void Process(PipelineArgs args)
{
#if DEBUG
BundleTable.EnableOptimizations = false;
#else
BundleTable.EnableOptimizations = true;
#endif
Register(BundleTable.Bundles);
}
private void Register(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/sc_ignore_bundles/rebootscripts").Include(
"~/js/jquery-{version}.js",
"~/js/bootstrap.js",
"~/js/modern-business.js",
"~/js/reboot.js",
"~/js/jquery.rateit.min.js"
));
bundles.Add(new StyleBundle("~/sc_ignore_bundles/rebootstyles").Include(
"~/css/bootstrap.css",
"~/css/theme.css",
"~/font-awesome/css/font-awesome.min.css",
"~/css/modern-business.css",
"~/css/reboot.css",
"~/css/rateit.css"
));
}
}
}
| 25.574468 | 86 | 0.531614 | [
"MIT"
] | cloud-explorer/reboot | Reboot.Core/MVC/RegisterBundles.cs | 1,204 | C# |
namespace PiControlPanel.Api.GraphQL.Extensions
{
using System.Linq;
using global::GraphQL.Builders;
using global::GraphQL.Types.Relay.DataObjects;
using PiControlPanel.Domain.Models.Hardware;
using PiControlPanel.Domain.Models.Paging;
/// <summary>
/// Contains extension methods to handle paging with GraphQL connections.
/// </summary>
public static class PagingExtensions
{
/// <summary>
/// Creates paging input object from GraphQL connection context.
/// </summary>
/// <typeparam name="T">The model generic type parameter.</typeparam>
/// <param name="context">The GraphQL connection context.</param>
/// <returns>The paging input object.</returns>
public static PagingInput GetPagingInput<T>(this ResolveConnectionContext<T> context)
{
return new PagingInput()
{
First = context.First,
After = context.After,
Last = context.Last,
Before = context.Before
};
}
/// <summary>
/// Creates a GraphQL connection from a paging output object.
/// </summary>
/// <typeparam name="T">The model generic type parameter.</typeparam>
/// <param name="pagingOutput">The paging output object.</param>
/// <returns>The GraphQL connection.</returns>
public static Connection<T> ToConnection<T>(this PagingOutput<T> pagingOutput)
where T : BaseTimedObject
{
var edges = pagingOutput.Result.Select((status, i) => new Edge<T>
{
Node = status,
Cursor = status.ID.ToString()
}).ToList();
return new Connection<T>()
{
Edges = edges,
TotalCount = pagingOutput.TotalCount,
PageInfo = new PageInfo
{
StartCursor = edges.FirstOrDefault()?.Cursor,
EndCursor = edges.LastOrDefault()?.Cursor,
HasPreviousPage = pagingOutput.HasPreviousPage,
HasNextPage = pagingOutput.HasNextPage,
}
};
}
}
}
| 36.672131 | 93 | 0.56236 | [
"MIT"
] | HritwikSinghal/pi-control-panel | src/Api/PiControlPanel.Api.GraphQL/Extensions/PagingExtensions.cs | 2,239 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace PartialDeployer
{
using System.IO;
using log4net;
public class folderMan
{
private static readonly ILog log = LogManager.GetLogger("folderMan");
string[] deliedList = (".md|.sublime-|.git|.gitignore|.gitattributes|.svn-base|sess_|.idea|log-|.less|test.|package\\|app\\storage\\sessions|bundle\\|storage\\").Split('|');
public bool ForceCopy(string fromPath, string fromFile, string toPath, string toFile)
{
if (!Directory.Exists(toPath))
{
Directory.CreateDirectory(toPath);
}
File.Copy(fromPath + fromFile, toPath + toFile, true);
return true;
}
public void DeleteFile(string fromFile)
{
File.Delete(fromFile);
}
private bool AllowedPattern(string path)
{
int loc = deliedList.Count(x => path.Contains(x));
return !(loc > 0);
}
public List<DirEntry> DirGetFolder(string sFolder)
{
log.Debug("DirGetFolder");
List<DirEntry> DirEntries = new List<DirEntry>();
DirectoryInfo dirInfo = new DirectoryInfo(sFolder);
DirectoryInfo[] dirFolders = dirInfo.GetDirectories("*.*", SearchOption.AllDirectories);
for (int i = 0; i < dirFolders.Length; i++)
{
if (AllowedPattern(dirFolders[i].FullName))
{
DirEntries.Add(new DirEntry()
{
EntryPath = dirFolders[i].FullName.Replace(sFolder, String.Empty),
EntryType = FtpEntryType.Folder
});
}
}
return DirEntries;
}
public bool IsFileExists(string fileName)
{
return File.Exists(fileName);
}
public List<DirEntry> DirGetFolderContents(string sFolder)
{
log.InfoFormat("Reading Folder : {0}", sFolder);
List<DirEntry> DirEntries = new List<DirEntry>();
DirectoryInfo dirInfo = new DirectoryInfo(sFolder);
if (dirInfo.Exists)
{
FileInfo[] dirFiles = dirInfo.GetFiles("*.*", SearchOption.AllDirectories);
for (int i = 0; i < dirFiles.Length; i++)
{
if (AllowedPattern(dirFiles[i].FullName))
{
DirEntry de = new DirEntry()
{
EntryPath = dirFiles[i].DirectoryName.Replace(sFolder, String.Empty) + "\\",
EntryName = dirFiles[i].Name,
EntryType = FtpEntryType.File,
DateModified = dirFiles[i].LastWriteTimeUtc
};
DirEntries.Add(de);
}
}
}
return DirEntries;
}
}
} | 33.053763 | 181 | 0.507807 | [
"MIT"
] | greatb/PartialDeployer | src/PartialDeployer/FolderMan.cs | 3,076 | C# |
namespace OneTwoOne.Module.Catalog.Areas.Catalog.ViewModels
{
public class CategoryTranslationForm
{
public string DefaultCultureName { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
}
| 22 | 60 | 0.659091 | [
"Apache-2.0"
] | microcapital/one2one | src/Modules/OneTwoOne.Module.Catalog/Areas/Catalog/ViewModels/CategoryTranslationForm.cs | 266 | C# |
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
namespace TestRail.Types
{
/// <inheritdoc />
/// <summary>stores information about a run</summary>
public class Run : BaseTestRailType
{
#region Public Properties
/// <summary>id of the run</summary>
public ulong? Id { get; private set; }
/// <summary>name of the run</summary>
public string Name { get; set; }
/// <summary>description of the run</summary>
public string Description { get; set; }
/// <summary>id of the suite associated with the run</summary>
public ulong? SuiteId { get; set; }
/// <summary>id of the milestone associated with the run</summary>
public ulong? MilestoneId { get; set; }
/// <summary>config for the run</summary>
public string Config { get; private set; }
/// <summary>true if the run has been completes</summary>
public bool? IsCompleted { get; private set; }
/// <summary>date on which the run which was completed</summary>
public DateTime? CompletedOn { get; private set; }
/// <summary>date on which the run which was created</summary>
public DateTime? CreatedOn { get; private set; }
/// <summary>number of tests in the plan that passed</summary>
public uint? PassedCount { get; private set; }
/// <summary>number of tests in the plan that are blocked</summary>
public uint? BlockedCount { get; private set; }
/// <summary>number of tests in the plan that are untested</summary>
public uint? UntestedCount { get; private set; }
/// <summary>number of tests in the plan that need to be retested</summary>
public uint? RetestCount { get; private set; }
/// <summary>number of tests in the plan that failed</summary>
public uint? FailedCount { get; private set; }
/// <summary>id of the project associated with the run</summary>
public ulong? ProjectId { get; private set; }
/// <summary>id of the plan associated with the run</summary>
public ulong? PlanId { get; private set; }
/// <summary>is of the user it is assigned to</summary>
public ulong? AssignedTo { get; set; }
/// <summary>true if the test run includes all test cases and false otherwise</summary>
public bool IncludeAll { get; set; }
/// <summary>the amount of tests in the test run with the respective custom status</summary>
public ulong CustomStatus1Count { get; private set; }
/// <summary>the amount of tests in the test run with the respective custom status</summary>
public ulong CustomStatus2Count { get; private set; }
/// <summary>the amount of tests in the test run with the respective custom status</summary>
public ulong CustomStatus3Count { get; private set; }
/// <summary>the amount of tests in the test run with the respective custom status</summary>
public ulong CustomStatus4Count { get; private set; }
/// <summary>the amount of tests in the test run with the respective custom status</summary>
public ulong CustomStatus5Count { get; private set; }
/// <summary>the amount of tests in the test run with the respective custom status</summary>
public ulong CustomStatus6Count { get; private set; }
/// <summary>the amount of tests in the test run with the respective custom status</summary>
public ulong CustomStatus7Count { get; private set; }
/// <summary>the address/URL of the test run in the user interface</summary>
public string Url { get; private set; }
/// <summary>an array of case IDs for the custom case selection</summary>
public HashSet<ulong> CaseIds { get; set; }
/// <summary>an array of case IDs for the custom case selection</summary>
public List<ulong> ConfigIds { get; set; }
#endregion Public Properties
#region Public Methods
/// <summary>string representation of the object</summary>
/// <returns>string representation of the object</returns>
public override string ToString()
{
return Name;
}
/// <summary>parses json into a run</summary>
/// <param name="json">json to parse</param>
/// <returns>run corresponding to the json</returns>
public static Run Parse(JObject json)
{
var run = new Run
{
JsonFromResponse = json,
Id = (ulong?)json["id"],
Name = (string)json["name"],
Description = (string)json["description"],
SuiteId = (ulong?)json["suite_id"],
MilestoneId = (ulong?)json["milestone_id"],
Config = (string)json["config"],
IsCompleted = (bool?)json["is_completed"],
CompletedOn = null == (int?)json["completed_on"] ? (DateTime?)null : new DateTime(1970, 1, 1).AddSeconds((int)json["completed_on"]),
CreatedOn = null == (int?)json["created_on"] ? (DateTime?)null : new DateTime(1970, 1, 1).AddSeconds((int)json["created_on"]),
PassedCount = (uint?)json["passed_count"],
BlockedCount = (uint?)json["blocked_count"],
UntestedCount = (uint?)json["untested_count"],
RetestCount = (uint?)json["retest_count"],
FailedCount = (uint?)json["failed_count"],
ProjectId = (ulong?)json["project_id"],
PlanId = (ulong?)json["plan_id"],
CustomStatus1Count = (ulong)json["custom_status1_count"],
CustomStatus2Count = (ulong)json["custom_status2_count"],
CustomStatus3Count = (ulong)json["custom_status3_count"],
CustomStatus4Count = (ulong)json["custom_status4_count"],
CustomStatus5Count = (ulong)json["custom_status5_count"],
CustomStatus6Count = (ulong)json["custom_status6_count"],
CustomStatus7Count = (ulong)json["custom_status7_count"],
AssignedTo = (ulong?)json["assignedto_id"],
IncludeAll = (bool)json["include_all"],
Url = (string)json["url"]
};
return run;
}
/// <summary>Creates a json object for this class</summary>
/// <returns>json object that represents this class</returns>
public JObject GetJson()
{
dynamic jsonParams = new JObject();
if (null != SuiteId)
{
jsonParams.suite_id = SuiteId;
}
if (!string.IsNullOrWhiteSpace(Name))
{
jsonParams.name = Name;
}
if (null != Description)
{
jsonParams.description = Description;
}
if (null != MilestoneId)
{
jsonParams.milestone_id = MilestoneId;
}
if (null != AssignedTo)
{
jsonParams.assignedto_id = AssignedTo;
}
jsonParams.include_all = IncludeAll;
if (null != CaseIds && 0 < CaseIds.Count)
{
var jarray = new JArray();
foreach (var caseId in CaseIds)
{
jarray.Add(caseId);
}
jsonParams.case_ids = jarray;
}
if (null != ConfigIds && 0 < ConfigIds.Count)
{
var jarray = new JArray();
foreach (var configId in ConfigIds)
{
jarray.Add(configId);
}
jsonParams.config_ids = jarray;
}
return jsonParams;
}
#endregion Public Methods
}
}
| 38.558252 | 148 | 0.574468 | [
"Apache-2.0"
] | Brrovko/testrail-client | TestRail/Types/Run.cs | 7,943 | C# |
using System;
namespace Lachain.Storage.State
{
public interface IStateManager : ISnapshotManager<IBlockchainSnapshot>
{
void SafeContext(Action callback);
T SafeContext<T>(Func<T> callback);
void Acquire();
void Release();
}
} | 19.466667 | 74 | 0.613014 | [
"Apache-2.0"
] | LATOKEN/lachain | src/Lachain.Storage/State/IStateManager.cs | 294 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// This source code is made available under the terms of the Microsoft Public License (MS-PL)
//Original code created by Matt Warren: http://iqtoolkit.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=19725
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Stump.ORM.SubSonic.Linq.Structure;
namespace Stump.ORM.SubSonic.Linq.Translation
{
/// <summary>
/// Rewrite aggregate expressions, moving them into same select expression that has the group-by clause
/// </summary>
public class AggregateRewriter : DbExpressionVisitor
{
ILookup<TableAlias, AggregateSubqueryExpression> lookup;
Dictionary<AggregateSubqueryExpression, Expression> map;
private AggregateRewriter(Expression expr)
{
this.map = new Dictionary<AggregateSubqueryExpression, Expression>();
this.lookup = AggregateGatherer.Gather(expr).ToLookup(a => a.GroupByAlias);
}
public static Expression Rewrite(Expression expr)
{
return new AggregateRewriter(expr).Visit(expr);
}
protected override Expression VisitSelect(SelectExpression select)
{
select = (SelectExpression)base.VisitSelect(select);
if (lookup.Contains(select.Alias))
{
List<ColumnDeclaration> aggColumns = new List<ColumnDeclaration>(select.Columns);
foreach (AggregateSubqueryExpression ae in lookup[select.Alias])
{
string name = "agg" + aggColumns.Count;
ColumnDeclaration cd = new ColumnDeclaration(name, ae.AggregateInGroupSelect);
this.map.Add(ae, new ColumnExpression(ae.Type, ae.GroupByAlias, name));
aggColumns.Add(cd);
}
return new SelectExpression(select.Alias, aggColumns, select.From, select.Where, select.OrderBy, select.GroupBy, select.IsDistinct, select.Skip, select.Take);
}
return select;
}
protected override Expression VisitAggregateSubquery(AggregateSubqueryExpression aggregate)
{
Expression mapped;
if (this.map.TryGetValue(aggregate, out mapped))
{
return mapped;
}
return this.Visit(aggregate.AggregateAsSubquery);
}
class AggregateGatherer : DbExpressionVisitor
{
List<AggregateSubqueryExpression> aggregates = new List<AggregateSubqueryExpression>();
private AggregateGatherer()
{
}
internal static List<AggregateSubqueryExpression> Gather(Expression expression)
{
AggregateGatherer gatherer = new AggregateGatherer();
gatherer.Visit(expression);
return gatherer.aggregates;
}
protected override Expression VisitAggregateSubquery(AggregateSubqueryExpression aggregate)
{
this.aggregates.Add(aggregate);
return base.VisitAggregateSubquery(aggregate);
}
}
}
} | 39.728395 | 174 | 0.63642 | [
"Apache-2.0"
] | Daymortel/Stump | src/Stump.ORM/SubSonic/Linq/Translation/AggregateRewriter.cs | 3,220 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace Pixiv
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
var APISettings = Configuration.GetSection("Pixiv:API");
services.Configure<APISettings>(APISettings);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
| 32.515625 | 109 | 0.604037 | [
"MIT"
] | ApexWeed/PixivMirror | src/Pixiv/Startup.cs | 2,083 | C# |
using System;
using System.Web.Http;
using System.Web.Mvc;
using ISPSystem.WebAPI.Areas.HelpPage.ModelDescriptions;
using ISPSystem.WebAPI.Areas.HelpPage.Models;
namespace ISPSystem.WebAPI.Areas.HelpPage.Controllers
{
/// <summary>
/// The controller that will handle requests for the help page.
/// </summary>
public class HelpController : Controller
{
private const string ErrorViewName = "Error";
public HelpController()
: this(GlobalConfiguration.Configuration)
{
}
public HelpController(HttpConfiguration config)
{
Configuration = config;
}
public HttpConfiguration Configuration { get; private set; }
public ActionResult Index()
{
ViewBag.DocumentationProvider = Configuration.Services.GetDocumentationProvider();
return View(Configuration.Services.GetApiExplorer().ApiDescriptions);
}
public ActionResult Api(string apiId)
{
if (!String.IsNullOrEmpty(apiId))
{
HelpPageApiModel apiModel = Configuration.GetHelpPageApiModel(apiId);
if (apiModel != null)
{
return View(apiModel);
}
}
return View(ErrorViewName);
}
public ActionResult ResourceModel(string modelName)
{
if (!String.IsNullOrEmpty(modelName))
{
ModelDescriptionGenerator modelDescriptionGenerator = Configuration.GetModelDescriptionGenerator();
ModelDescription modelDescription;
if (modelDescriptionGenerator.GeneratedModels.TryGetValue(modelName, out modelDescription))
{
return View(modelDescription);
}
}
return View(ErrorViewName);
}
}
} | 30.269841 | 115 | 0.599371 | [
"MIT"
] | MayconKlopper/Desafio-ISP | ISPSystem/ISPSystem.WebAPI/Areas/HelpPage/Controllers/HelpController.cs | 1,907 | C# |
using Microsoft.Owin;
using Owin;
[assembly: OwinStartupAttribute(typeof(Lab41MvcMovie.Startup))]
namespace Lab41MvcMovie
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
}
}
}
| 18.4 | 63 | 0.655797 | [
"MIT"
] | cascadianrebel/Lab41MvcMovie | Lab41MvcMovie/Startup.cs | 278 | C# |
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using RimWorld;
using UnityEngine;
using Verse;
using Verse.AI;
namespace RationalRomance_Code;
public class JobDriver_ProposeDate : JobDriver
{
public bool successfulPass = true;
private Pawn actor => GetActor();
private Pawn TargetPawn => TargetThingA as Pawn;
private Building_Bed TargetBed => TargetThingB as Building_Bed;
private TargetIndex TargetPawnIndex => TargetIndex.A;
private TargetIndex TargetBedIndex => TargetIndex.B;
public override bool TryMakePreToilReservations(bool errorOnFailed)
{
return true;
}
private bool TryFindUnforbiddenDatePath(Pawn p1, Pawn p2, IntVec3 root, out List<IntVec3> result)
{
var StartRadialIndex = GenRadial.NumCellsInRadius(14f);
var EndRadialIndex = GenRadial.NumCellsInRadius(2f);
var RadialIndexStride = 3;
var intVec3s = new List<IntVec3> { root };
var intVec3 = root;
for (var i = 0; i < 8; i++)
{
var invalid = IntVec3.Invalid;
var single1 = -1f;
for (var j = StartRadialIndex; j > EndRadialIndex; j -= RadialIndexStride)
{
var radialPattern = intVec3 + GenRadial.RadialPattern[j];
if (!radialPattern.InBounds(p1.Map) || !radialPattern.Standable(p1.Map) ||
radialPattern.IsForbidden(p1) || radialPattern.IsForbidden(p2) ||
radialPattern.GetTerrain(p1.Map).avoidWander ||
!GenSight.LineOfSight(intVec3, radialPattern, p1.Map) || radialPattern.Roofed(p1.Map) ||
PawnUtility.KnownDangerAt(radialPattern, p1.Map, p1) ||
PawnUtility.KnownDangerAt(radialPattern, p1.Map, p2))
{
continue;
}
var lengthManhattan = 10000f;
foreach (var vec3 in intVec3s)
{
lengthManhattan += (vec3 - radialPattern).LengthManhattan;
}
float lengthManhattan1 = (radialPattern - root).LengthManhattan;
if (lengthManhattan1 > 40f)
{
lengthManhattan *= Mathf.InverseLerp(70f, 40f, lengthManhattan1);
}
if (intVec3s.Count >= 2)
{
var item = intVec3s[intVec3s.Count - 1] - intVec3s[intVec3s.Count - 2];
var angleFlat = item.AngleFlat;
var angleFlat1 = (radialPattern - intVec3).AngleFlat;
float single;
if (angleFlat1 <= angleFlat)
{
angleFlat -= 360f;
single = angleFlat1 - angleFlat;
}
else
{
single = angleFlat1 - angleFlat;
}
if (single > 110f)
{
lengthManhattan *= 0.01f;
}
}
if (intVec3s.Count >= 4 &&
(intVec3 - root).LengthManhattan < (radialPattern - root).LengthManhattan)
{
lengthManhattan *= 1E-05f;
}
if (!(lengthManhattan > single1))
{
continue;
}
invalid = radialPattern;
single1 = lengthManhattan;
}
if (single1 < 0f)
{
result = null;
return false;
}
intVec3s.Add(invalid);
intVec3 = invalid;
}
intVec3s.Add(root);
result = intVec3s;
return true;
}
private bool IsTargetPawnOkay()
{
return !TargetPawn.Dead && !TargetPawn.Downed;
}
private bool TryFindMostBeautifulRootInDistance(int distance, Pawn p1, Pawn p2, out IntVec3 best)
{
best = default;
var list = new List<IntVec3>();
for (var i = 0; i < 200; i++)
{
if (CellFinder.TryFindRandomCellNear(p1.Position, p1.Map, distance,
c => c.InBounds(p1.Map) && !c.IsForbidden(p1) && !c.IsForbidden(p2) &&
p1.CanReach(c, PathEndMode.OnCell, Danger.Some), out var item))
{
list.Add(item);
}
}
bool result;
if (list.Count == 0)
{
result = false;
Log.Message("No date walk destination found.");
}
else
{
var list2 = (from c in list
orderby BeautyUtility.AverageBeautyPerceptible(c, p1.Map) descending
select c).ToList();
best = list2.FirstOrDefault();
list2.Reverse();
Log.Message("Date walk destinations found from beauty " +
BeautyUtility.AverageBeautyPerceptible(best, p1.Map) + " to " +
BeautyUtility.AverageBeautyPerceptible(list2.FirstOrDefault(), p1.Map));
result = true;
}
return result;
}
[DebuggerHidden]
protected override IEnumerable<Toil> MakeNewToils()
{
if (!SexualityUtilities.IsFree(TargetPawn))
{
yield break;
}
yield return Toils_Goto.GotoThing(TargetPawnIndex, PathEndMode.Touch);
var AskOut = new Toil();
AskOut.AddFailCondition(() => !IsTargetPawnOkay());
AskOut.defaultCompleteMode = ToilCompleteMode.Delay;
AskOut.initAction = delegate
{
ticksLeftThisToil = 50;
FleckMaker.ThrowMetaIcon(GetActor().Position, GetActor().Map, FleckDefOf.Heart);
};
yield return AskOut;
var AwaitResponse = new Toil
{
defaultCompleteMode = ToilCompleteMode.Instant,
initAction = delegate
{
successfulPass = SexualityUtilities.IsFree(TargetPawn);
FleckMaker.ThrowMetaIcon(TargetPawn.Position, TargetPawn.Map,
successfulPass ? FleckDefOf.Heart : FleckDefOf.IncapIcon);
}
};
AwaitResponse.AddFailCondition(() => !successfulPass);
yield return AwaitResponse;
if (successfulPass)
{
yield return new Toil
{
defaultCompleteMode = ToilCompleteMode.Instant,
initAction = delegate
{
var jobDateLead = new Job(RRRJobDefOf.JobDateLead);
if (!TryFindMostBeautifulRootInDistance(40, pawn, TargetPawn, out var root))
{
return;
}
if (TryFindUnforbiddenDatePath(pawn, TargetPawn, root, out var list))
{
Log.Message("Date walk path found.");
jobDateLead.targetQueueB = new List<LocalTargetInfo>();
for (var i = 1; i < list.Count; i++)
{
jobDateLead.targetQueueB.Add(list[i]);
}
jobDateLead.locomotionUrgency = LocomotionUrgency.Amble;
jobDateLead.targetA = TargetPawn;
actor.jobs.jobQueue.EnqueueFirst(jobDateLead);
var job2 = new Job(RRRJobDefOf.JobDateFollow)
{
locomotionUrgency = LocomotionUrgency.Amble, targetA = actor
};
TargetPawn.jobs.jobQueue.EnqueueFirst(job2);
TargetPawn.jobs.EndCurrentJob(JobCondition.InterruptOptional);
actor.jobs.EndCurrentJob(JobCondition.InterruptOptional);
}
else
{
Log.Message("No date walk path found.");
}
}
};
}
}
} | 35.23913 | 108 | 0.508698 | [
"MIT"
] | emipa606/RationalRomance | Source/Rainbeau's Rational Romance/JobDriver_ProposeDate.cs | 8,105 | C# |
using System;
using System.Runtime.InteropServices;
using Microsoft.AspNetCore.Authentication.GssKerberos.Disposables;
using static Microsoft.AspNetCore.Authentication.GssKerberos.Native.Krb5Interop;
namespace Microsoft.AspNetCore.Authentication.GssKerberos
{
public class GssKeytabCredential : GssCredential
{
private IntPtr _credentials;
private IntPtr _acceptorName;
protected internal override IntPtr Credentials => _credentials;
public GssKeytabCredential(string principal, string keytab, CredentialUsage usage, uint expiry = GSS_C_INDEFINITE)
{
// allocate a gss buffer and copy the principal name to it
using (var gssNameBuffer = GssBuffer.FromString(principal))
{
uint minorStatus = 0;
uint majorStatus = 0;
// use the buffer to import the name into a gss_name
majorStatus = gss_import_name(
out minorStatus,
ref gssNameBuffer.Value,
ref GssNtPrincipalName,
out var acceptorName
);
if (majorStatus != GSS_S_COMPLETE)
throw new GssException("The GSS provider was unable to import the supplied principal name",
majorStatus, minorStatus, GssNtHostBasedService);
majorStatus = gss_acquire_cred(
out minorStatus,
acceptorName,
expiry,
ref GssSpnegoMechOidSet,
(int)usage,
ref _credentials,
IntPtr.Zero, // dont mind what mechs we got
out var actualExpiry);
if (majorStatus != GSS_S_COMPLETE)
throw new GssException("The GSS Provider was unable aquire credentials for authentication",
majorStatus, minorStatus, GssSpnegoMechOidDesc);
}
}
public override void Dispose()
{
uint minorStatus = 0;
uint majorStatus = 0;
majorStatus = gss_release_name(out minorStatus, ref _acceptorName);
if (majorStatus != GSS_S_COMPLETE)
{
throw new GssException("The GSS provider was unable to release the princpal name handle",
majorStatus, minorStatus, GssNtHostBasedService);
}
majorStatus = gss_release_cred(out minorStatus, ref _credentials);
if (majorStatus != GSS_S_COMPLETE)
{
throw new GssException("The GSS provider was unable to release the credential handle",
majorStatus, minorStatus, GssNtHostBasedService);
}
}
}
}
| 39.097222 | 122 | 0.582593 | [
"MIT"
] | ianclegg/aspnetcore-kerberos | Microsoft.AspNetCore.Authentication.GssKerberos/Gss/GssKeytabCredentials.cs | 2,817 | C# |
using System;
using BLD.Helpers;
/// <summary>
/// GET Entities from connected Catalyst
/// </summary>
public interface ICatalyst : IDisposable
{
/// <summary>
/// url for content server
/// </summary>
public string contentUrl { get; }
/// <summary>
/// url for lambdas
/// </summary>
public string lambdasUrl { get; }
/// <summary>
/// get scenes deployed in parcels
/// </summary>
/// <param name="parcels">parcels to get scenes from</param>
/// <returns>promise of an array of scenes entities</returns>
Promise<CatalystSceneEntityPayload[]> GetDeployedScenes(string[] parcels);
/// <summary>
/// get scenes deployed in parcels
/// </summary>
/// <param name="parcels">parcels to get scenes from</param>
/// <param name="cacheMaxAgeSeconds">discard cache if it's older than cacheMaxAgeSeconds ago</param>
/// <returns>promise of an array of scenes entities</returns>
Promise<CatalystSceneEntityPayload[]> GetDeployedScenes(string[] parcels, float cacheMaxAgeSeconds);
/// <summary>
/// get entities of entityType
/// </summary>
/// <param name="entityType">type of the entity to fetch. see CatalystEntitiesType class</param>
/// <param name="pointers">pointers to fetch</param>
/// <returns>promise of a string containing catalyst response json</returns>
Promise<string> GetEntities(string entityType, string[] pointers);
/// <summary>
/// wraps a WebRequest inside a promise and cache it result
/// </summary>
/// <param name="url">url to make the request to</param>
/// <returns>promise of the server response</returns>
Promise<string> Get(string url);
} | 35.604167 | 104 | 0.660035 | [
"Apache-2.0"
] | belandproject/unity-renderer | unity-renderer/Assets/Scripts/MainScripts/BLD/ServiceProviders/Catalyst/Interfaces/ICatalyst.cs | 1,711 | C# |
Subsets and Splits