content
stringlengths 5
1.04M
| avg_line_length
float64 1.75
12.9k
| max_line_length
int64 2
244k
| alphanum_fraction
float64 0
0.98
| licenses
list | repository_name
stringlengths 7
92
| path
stringlengths 3
249
| size
int64 5
1.04M
| lang
stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
using System;
using System.Collections.Generic;
using System.Linq;
namespace PartyReservationFilterModule
{
class Program
{
static void Main(string[] args)
{
List<string> invites = Console.ReadLine()
.Split(" ", StringSplitOptions.RemoveEmptyEntries)
.ToList();
List<string> filters = new List<string>();
while (true)
{
string input = Console.ReadLine();
if (input == "Print")
{
break;
}
string[] parts = input.Split(";", StringSplitOptions.RemoveEmptyEntries);
if (parts[0] == "Add filter")
{
filters.Add(parts[1] + " " + parts[2]);
}
else if (parts[0] == "Remove filter")
{
filters.Remove(parts[1] + " " + parts[2]);
}
}
foreach (var filter in filters)
{
string[] parts = filter.Split(" ");
if (parts[0] == "Starts")
{
invites = invites.Where(p=> !p.StartsWith((parts[2]))).ToList();
}
else if (parts[0] == "Ends")
{
invites = invites.Where(p => !p.EndsWith((parts[2]))).ToList();
}
else if (parts[0] == "Length")
{
invites = invites.Where(p => p.Length != int.Parse(parts[1])).ToList();
}
else if (parts[0] == "Contains")
{
invites = invites.Where(p => !p.Contains(parts[1])).ToList();
}
}
if (invites.Any())
{
Console.WriteLine(string.Join(" ", invites));
}
}
}
}
| 30.380952
| 91
| 0.400209
|
[
"MIT"
] |
Siafarikas/SoftUni
|
Advanced/FunctionalProgramming2/PartyReservationFilterModule/Program.cs
| 1,916
|
C#
|
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Ruzzie.Common.Numerics.Statistics;
namespace Ruzzie.Common.UnitTests
{
public static class RandomnessTester
{
public static RandomnessTestResult TestInt(Random simpleRandom, int maxValue = int.MaxValue, int numberOfSamples = 10000)
{
var sampleResult = RunSamples(simpleRandom, numberOfSamples, maxValue);
var randomnessTestResult = new RandomnessTestResult { SampleResult = sampleResult };
return randomnessTestResult;
}
public static RandomnessTestResult TestBytes(Random simpleRandom, int numberOfSamples = 10000)
{
var sampleResult = RunSamplesBytes(simpleRandom, numberOfSamples, out var samples);
var randomnessTestResult = new RandomnessTestResult { SampleResult = sampleResult };
randomnessTestResult.Samples = samples;
return randomnessTestResult;
}
private static SampleResult RunSamples(Random random, int numberOfSamples, int maxValue = int.MaxValue)
{
var histogram = new SortedDictionary<int, int>();
double average = 0;
for (int i = 0; i < numberOfSamples; i++)
{
int currentNumber = random.Next(maxValue);
average = Average.StreamAverage(average, currentNumber, i);
if (!histogram.ContainsKey(currentNumber))
{
histogram[currentNumber] = 1;
}
else
{
histogram[currentNumber] += 1;
}
}
double chisq = Common.Numerics.Distributions.ChiSquared.ChiSquaredP(maxValue, numberOfSamples, histogram);
double pochi = Common.Numerics.Distributions.ChiSquared.ProbabilityOfChiSquared(chisq, maxValue); // closer to 0.4 - 0.5 is better, <= 0.1 && >= 0.9 is bad
double entropy = histogram.CalculateEntropy(numberOfSamples);//must be above 3, higher is better
return new SampleResult(average, chisq, pochi, entropy);
}
private static SampleResult RunSamplesBytes(Random random, int numberOfSamples, out byte[] samples)
{
Dictionary<int, int> histogram = new Dictionary<int, int>(255);
samples = new byte[numberOfSamples];
double average = 0;
for (int i = 0; i < numberOfSamples; i++)
{
byte currentNumber = random.NextBytes(1)[0];
samples[i] = currentNumber;
average = Average.StreamAverage(average, currentNumber, i);
if (!histogram.ContainsKey(currentNumber))
{
histogram[currentNumber] = 1;
}
else
{
histogram[currentNumber] += 1;
}
}
double chisq = 0;
double pochi = 0;
Task calculateChis =
#if NET40
new Task( () =>
#else
Task.Run(() =>
#endif
{
chisq = Common.Numerics.Distributions.ChiSquared.ChiSquaredP(byte.MaxValue + 1, numberOfSamples, histogram);
pochi = Common.Numerics.Distributions.ChiSquared.ProbabilityOfChiSquared(chisq, byte.MaxValue + 1);// closer to 0.4 - 0.5 is better, <= 0.1 && >= 0.9 is bad
});
Task<double> calculateEntropy =
#if NET40
new Task<double>( () =>
#else
Task.Run(() =>
#endif
histogram.CalculateEntropy(numberOfSamples) /*must be above 3, higher is better*/);
calculateChis.Wait();
return new SampleResult(average, chisq, pochi, calculateEntropy.Result);
}
}
public class RandomnessTestResult
{
public SampleResult SampleResult { get; set; }
// ReSharper disable once UnusedAutoPropertyAccessor.Global
public byte[] Samples { get; set; }
}
public struct SampleResult
{
private readonly double _average;
private readonly double _chi;
private readonly double _poChi;
private readonly double _entropy;
public SampleResult(double average, double chi, double poChi, double entropy)
{
_average = average;
_chi = chi;
_poChi = poChi;
_entropy = entropy;
}
public double Average
{
get { return _average; }
}
public double Chi
{
get { return _chi; }
}
public double PoChi
{
get { return _poChi; }
}
public double Entropy
{
get { return _entropy; }
}
}
}
| 33.095238
| 172
| 0.56444
|
[
"MIT"
] |
Ruzzie/Ruzzie.Common
|
src/Ruzzie.Common/Ruzzie.Common.UnitTests/RandomnessTester.cs
| 4,867
|
C#
|
using UnityEngine;
using System.Collections;
public class FpsDisplay : MonoBehaviour
{
float deltaTime = 0.0f;
SimpleValueDisplayer.ValueHook fpsHook;
SimpleValueDisplayer.ValueHook msPerFrameHook;
void Start()
{
fpsHook = SimpleValueDisplayer.Instance.RegisterValue();
msPerFrameHook = SimpleValueDisplayer.Instance.RegisterValue();
}
void OnDestroy()
{
fpsHook.Dispose();
msPerFrameHook.Dispose();
}
void Update()
{
deltaTime += (Time.unscaledDeltaTime - deltaTime) * 0.1f;
float msec = deltaTime * 1000.0f;
float fps = 1.0f / deltaTime;
string msString = string.Format("Ms: {0:0.0}", msec);
string fpsString = string.Format("Fps: {0:0.}", fps);
msPerFrameHook.UpdateValue(msString);
fpsHook.UpdateValue(fpsString);
}
}
| 28.066667
| 65
| 0.657957
|
[
"MIT"
] |
martin-favre/Dorfaclysm3D
|
Assets/Scripts/FpsDisplay.cs
| 844
|
C#
|
namespace ClearHl7.Codes.V230
{
/// <summary>
/// HL7 Version 2 Table 0008 - Acknowledgment Code.
/// </summary>
/// <remarks>https://www.hl7.org/fhir/v2/0008</remarks>
public enum CodeAcknowledgmentCode
{
/// <summary>
/// AA - Original mode: Application Accept - Enhanced mode: Application acknowledgment: Accept.
/// </summary>
OriginalModeAcceptEnhancedModeAcknowledgmentAccept,
/// <summary>
/// AE - Original mode: Application Error - Enhanced mode: Application acknowledgment: Error.
/// </summary>
OriginalModeErrorEnhancedModeAcknowledgmentError,
/// <summary>
/// AR - Original mode: Application Reject - Enhanced mode: Application acknowledgment: Reject.
/// </summary>
OriginalModeRejectEnhancedModeAcknowledgmentReject,
/// <summary>
/// CA - Enhanced mode: Accept acknowledgment: Commit Accept.
/// </summary>
EnhancedModeAcceptAcknowledgmentCommitAccept,
/// <summary>
/// CE - Enhanced mode: Accept acknowledgment: Commit Error.
/// </summary>
EnhancedModeAcceptAcknowledgmentCommitError,
/// <summary>
/// CR - Enhanced mode: Accept acknowledgment: Commit Reject.
/// </summary>
EnhancedModeAcceptAcknowledgmentCommitReject
}
}
| 34.275
| 103
| 0.633115
|
[
"MIT"
] |
kamlesh-microsoft/clear-hl7-net
|
src/ClearHl7.Codes/V230/CodeAcknowledgmentCode.cs
| 1,373
|
C#
|
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Statiq.Common;
namespace Statiq.Core
{
/// <summary>
/// Starts a system process.
/// </summary>
/// <remarks>
/// This module can start both foreground and background processes. If the process
/// is a foreground process (the default), the module will wait for it to return
/// and output a document with the process standard output as it's content.
/// If the process is a background process, the module will fork it and let it run,
/// but no output document will be generated and it will log with a debug level.
/// </remarks>
/// <category name="Extensibility" />
public class StartProcess : ParallelSyncMultiConfigModule, IDisposable
{
/// <summary>
/// A metadata key that contains the process exit code.
/// </summary>
public const string ExitCode = nameof(ExitCode);
/// <summary>
/// A metadata key that contains any error data from the process.
/// </summary>
public const string ErrorData = nameof(ErrorData);
// Config keys
private const string FileName = nameof(FileName);
private const string Arguments = nameof(Arguments);
private const string WorkingDirectory = nameof(WorkingDirectory);
private const string Timeout = nameof(Timeout);
private const string ContinueOnErrorKey = nameof(ContinueOnErrorKey);
private const string KeepContentKey = nameof(KeepContentKey);
private const string EnvironmentVariables = nameof(EnvironmentVariables);
private const string LogOutputKey = nameof(LogOutputKey);
private const string LogErrorsKey = nameof(LogErrorsKey);
private const string HideArgumentsKey = nameof(HideArgumentsKey);
private readonly ConcurrentBag<ProcessLauncher> _processLaunchers = new ConcurrentBag<ProcessLauncher>();
private bool _background;
private bool _onlyOnce;
private bool _executed;
private Func<int, bool> _isErrorExitCode = x => x != 0;
/// <summary>
/// Starts a process for the specified file name and arguments.
/// </summary>
/// <param name="fileName">The file name of the process to start.</param>
public StartProcess(Config<string> fileName)
: this(fileName, Config.FromValue((string)null))
{
}
/// <summary>
/// Starts a process for the specified file name and arguments.
/// </summary>
/// <param name="fileName">The file name of the process to start.</param>
/// <param name="arguments">The arguments to pass to the process.</param>
public StartProcess(Config<string> fileName, Config<string> arguments)
: base(
new Dictionary<string, IConfig>
{
{ FileName, fileName.ThrowIfNull(nameof(fileName)) },
{ Arguments, arguments.ThrowIfNull(nameof(arguments)) },
{ LogErrorsKey, Config.FromValue(true) }
},
false)
{
}
/// <summary>
/// Appends an argument to the command.
/// </summary>
/// <param name="argument">The argument to append.</param>
/// <param name="quoted">Whether the argument should be quoted or not.</param>
/// <returns>The current module instance.</returns>
public StartProcess WithArgument(Config<string> argument, bool quoted = false)
{
argument.ThrowIfNull(nameof(argument));
return (StartProcess)CombineConfig(Arguments, argument, (first, second) =>
{
string space = first is null || second is null ? string.Empty : " ";
first ??= string.Empty;
second = second is null ? string.Empty : (quoted ? "\"" + second + "\"" : second);
return first + space + second;
});
}
/// <summary>
/// Appends an argument to the command.
/// </summary>
/// <param name="name">The name of the argument to append including any prefixes like a dash or slash.</param>
/// <param name="value">The value of the argument.</param>
/// <param name="quoted">Whether the value should be quoted or not.</param>
/// <returns>The current module instance.</returns>
public StartProcess WithArgument(Config<string> name, Config<string> value, bool quoted = false) =>
WithArgument(name.CombineWith(value, (name, value) =>
{
string space = name is null || value is null ? string.Empty : " ";
name ??= string.Empty;
value = value is null ? string.Empty : (quoted ? "\"" + value + "\"" : value);
return name + space + value;
}));
/// <summary>
/// Appends an argument to the command.
/// </summary>
/// <param name="argument">The argument to append including any prefixes like a dash or slash.</param>
/// <returns>The current module instance.</returns>
public StartProcess WithArgument(Config<StartProcessArgument> argument) =>
WithArgument(argument.Transform(arg =>
{
if (arg is null)
{
return string.Empty;
}
string space = arg.Name is null || arg.Value is null ? string.Empty : " ";
arg.Name ??= string.Empty;
arg.Value = arg.Value is null ? string.Empty : (arg.Quoted ? "\"" + arg.Value + "\"" : arg.Value);
return arg.Name + space + arg.Value;
}));
/// <summary>
/// Appends arguments to the command.
/// </summary>
/// <param name="arguments">The arguments to append including any prefixes like a dash or slash.</param>
/// <returns>The current module instance.</returns>
public StartProcess WithArguments(Config<IReadOnlyList<StartProcessArgument>> arguments) =>
WithArgument(arguments.Transform(args =>
{
if (args is null)
{
return string.Empty;
}
string combined = string.Empty;
foreach (StartProcessArgument arg in args)
{
if (arg is object)
{
string space = arg.Name is null || arg.Value is null ? string.Empty : " ";
arg.Name ??= string.Empty;
arg.Value = arg.Value is null ? string.Empty : (arg.Quoted ? "\"" + arg.Value + "\"" : arg.Value);
string prefix = combined.Length > 0 ? " " : string.Empty;
combined = combined + prefix + arg.Name + space + arg.Value;
}
}
return combined;
}));
/// <summary>
/// Sets the working directory to use for the process relative to the root path.
/// </summary>
/// <param name="workingDirectory">The working directory.</param>
/// <returns>The current module instance.</returns>
public StartProcess WithWorkingDirectory(Config<string> workingDirectory) =>
(StartProcess)SetConfig(WorkingDirectory, workingDirectory);
/// <summary>
/// Sets process-specific environment variables.
/// </summary>
/// <param name="environmentVariables">The environment variables to set.</param>
/// <returns>The current module instance.</returns>
public StartProcess WithEnvironmentVariables(Config<IEnumerable<KeyValuePair<string, string>>> environmentVariables)
{
environmentVariables.ThrowIfNull(nameof(environmentVariables));
return (StartProcess)CombineConfig(EnvironmentVariables, environmentVariables, (first, second) => second is null ? first : first?.Concat(second) ?? second);
}
/// <summary>
/// Sets a process-specific environment variable.
/// </summary>
/// <param name="environmentVariable">The name and value of the environment variable to set.</param>
/// <returns>The current module instance.</returns>
public StartProcess WithEnvironmentVariable(Config<KeyValuePair<string, string>> environmentVariable)
{
environmentVariable.ThrowIfNull(nameof(environmentVariable));
return WithEnvironmentVariables(environmentVariable.MakeEnumerable());
}
/// <summary>
/// Sets a timeout in milliseconds before the process will be terminated.
/// </summary>
/// <remarks>
/// This has no effect for background processes.
/// </remarks>
/// <param name="timeout">The timeout in milliseconds.</param>
/// <returns>The current module instance.</returns>
public StartProcess WithTimeout(Config<int> timeout) => (StartProcess)SetConfig(Timeout, timeout);
/// <summary>
/// Starts the process and leaves it running in the background.
/// </summary>
/// <remarks>
/// If the process is a background process, the module will fork it and let it run,
/// but no output document will be generated and it will log with a debug level.
/// </remarks>
/// <param name="background"><c>true</c> to start this process in the background, <c>false</c> otherwise.</param>
/// <param name="onlyOnce">
/// <c>true</c> to start the process the first time the module is executed and not on re-execution,
/// <c>false</c> to start a new process on every execution.
/// </param>
/// <returns>The current module instance.</returns>
public StartProcess AsBackground(bool background = true, bool onlyOnce = true)
{
_background = background;
_onlyOnce = onlyOnce;
return this;
}
/// <summary>
/// Only starts the process on the first module execution.
/// </summary>
/// <param name="onlyOnce">
/// <c>true</c> to start the process the first time the module is executed and not on re-execution,
/// <c>false</c> to start a new process on every execution.
/// </param>
/// <returns>The current module instance.</returns>
public StartProcess OnlyOnce(bool onlyOnce = true)
{
_onlyOnce = onlyOnce;
return this;
}
/// <summary>
/// Toggles whether to hide the arguments list when logging the process command.
/// </summary>
/// <param name="hideArguments"><c>true</c> or <c>null</c> to hide the arguments, <c>false</c> otherwise.</param>
/// <returns>The current module instance.</returns>
public StartProcess HideArguments(Config<bool> hideArguments = null) => (StartProcess)SetConfig(HideArgumentsKey, hideArguments ?? true);
/// <summary>
/// Toggles whether to log standard process output as information messages.
/// </summary>
/// <remarks>
/// By default, standard process output is only logged as debug messages.
/// </remarks>
/// <param name="logOutput"><c>true</c> or <c>null</c> to log standard process output as information messages, <c>false</c> to log them as debug messages.</param>
/// <returns>The current module instance.</returns>
public StartProcess LogOutput(Config<bool> logOutput = null) => (StartProcess)SetConfig(LogOutputKey, logOutput ?? true);
/// <summary>
/// Toggles whether to log error process output as error messages.
/// </summary>
/// <remarks>
/// By default, error process output is logged as error messages.
/// </remarks>
/// <param name="logErrors"><c>true</c> or <c>null</c> to log error process output as error messages, <c>false</c> to log them as debug messages.</param>
/// <returns>The current module instance.</returns>
public StartProcess LogErrors(Config<bool> logErrors = null) => (StartProcess)SetConfig(LogErrorsKey, logErrors ?? true);
/// <summary>
/// Toggles throwing an exception if the process exits with a non-zero exit code.
/// </summary>
/// <remarks>
/// By default the module will throw an exception if the process exits with a non-zero exit code.
/// </remarks>
/// <param name="continueOnError"><c>true</c> or <c>null</c> to continue when the process exits with a non-zero exit code, <c>false</c> to throw an exception.</param>
/// <returns>The current module instance.</returns>
public StartProcess ContinueOnError(Config<bool> continueOnError = null) => (StartProcess)SetConfig(ContinueOnErrorKey, continueOnError ?? true);
/// <summary>
/// Provides a function that determines if the exit code from the process was an error.
/// </summary>
/// <remarks>
/// By default any non-zero exit code is considered an error. Some processes return non-zero
/// exit codes to indicate success and this lets you treat those as successful.
/// </remarks>
/// <param name="isErrorExitCode">A function that determines if the exit code is an error by returning <c>true</c>.</param>
/// <returns>The current module instance.</returns>
public StartProcess WithErrorExitCode(Func<int, bool> isErrorExitCode)
{
_isErrorExitCode = isErrorExitCode.ThrowIfNull(nameof(isErrorExitCode));
return this;
}
/// <summary>
/// Keeps the existing document content instead of replacing it with the process output.
/// </summary>
/// <remarks>
/// This has no effect if the process is a background process.
/// </remarks>
/// <param name="keepContent">
/// <c>true</c> or <c>null</c> to keep the existing document content,
/// <c>false</c> to replace it with the process output.
/// </param>
/// <returns>The current module instance.</returns>
public StartProcess KeepContent(Config<bool> keepContent = null) => (StartProcess)SetConfig(KeepContentKey, keepContent ?? true);
protected override IEnumerable<IDocument> ExecuteConfig(IDocument input, IExecutionContext context, IMetadata values)
{
// Only execute once if requested
if (_onlyOnce && _executed)
{
context.LogDebug("Process was configured to execute once, returning input document");
return input.Yield();
}
_executed = true;
// Get the filename
string fileName = values.GetString(FileName);
if (fileName.IsNullOrWhiteSpace())
{
context.LogDebug("Provided file name was null or empty, skipping and returning input document");
return input.Yield();
}
// Create the process launcher
bool continueOnError = values.GetBool(ContinueOnErrorKey);
bool logOutput = values.GetBool(LogOutputKey);
bool logErrors = values.GetBool(LogErrorsKey);
bool hideArguments = values.GetBool(HideArgumentsKey);
ProcessLauncher processLauncher = new ProcessLauncher(fileName)
{
IsBackground = _background,
ContinueOnError = continueOnError,
LogOutput = logOutput,
LogErrors = logErrors,
HideArguments = hideArguments,
IsErrorExitCode = _isErrorExitCode
};
_processLaunchers.Add(processLauncher);
// Set arguments
string arguments = values.GetString(Arguments);
if (!arguments.IsNullOrEmpty())
{
processLauncher.Arguments = arguments;
}
// Set working directory
string workingDirectory = values.GetString(WorkingDirectory);
if (workingDirectory.IsNullOrWhiteSpace())
{
processLauncher.WorkingDirectory = context.FileSystem.RootPath.FullPath;
}
else
{
processLauncher.WorkingDirectory = context.FileSystem.RootPath.Combine(workingDirectory).FullPath;
}
// Set environment variables for the process
processLauncher.WithEnvironmentVariables(values.GetList(EnvironmentVariables, Array.Empty<KeyValuePair<string, string>>()));
// Start the process
bool keepContent = values.GetBool(KeepContentKey);
using (Stream outputStream = _background || keepContent ? null : context.GetContentStream())
{
using (StreamWriter outputWriter = outputStream == null ? null : new StreamWriter(outputStream, leaveOpen: true))
{
using (StringWriter errorWriter = !_background && continueOnError ? new StringWriter() : null)
{
int exitCode;
try
{
exitCode = processLauncher.StartNew(outputWriter, errorWriter, context.Logger, context, context.CancellationToken);
}
catch (Exception ex)
{
throw new LoggedException(ex);
}
// If this is a background process, let it run and just return the original document
if (processLauncher.IsBackground)
{
return input.Yield();
}
// Set the metadata items and return
MetadataItems metadata = new MetadataItems
{
{ ExitCode, exitCode }
};
string errorContent = errorWriter?.ToString();
if (!errorContent.IsNullOrEmpty())
{
metadata.Add(ErrorData, errorContent);
}
return context.CloneOrCreateDocument(
input,
metadata,
outputStream is null ? null : context.GetContentProvider(outputStream))
.Yield();
}
}
}
}
public void Dispose()
{
foreach (ProcessLauncher processLauncher in _processLaunchers)
{
processLauncher.Dispose();
}
}
}
}
| 46.841463
| 174
| 0.5824
|
[
"MIT"
] |
flcdrg/Statiq.Framework
|
src/core/Statiq.Core/Modules/Extensibility/StartProcess.cs
| 19,207
|
C#
|
using UnityEngine;
using System.Collections;
using System;
namespace UnityAtts
{
/// <summary>
/// Constrains an int field to a minimum value.
/// </summary>
public class MinAttribute : IntConstraintAttribute
{
public int MinValue { get; set; }
public MinAttribute(int min)
{
MinValue = min;
}
public override int ConstrainValue(int value)
{
return Mathf.Max(value, MinValue);
}
}
}
| 19.64
| 54
| 0.580448
|
[
"MIT"
] |
konikun/unityatts
|
UnityAtts/Assets/UnityAtts/Scripts/MinAttribute.cs
| 493
|
C#
|
namespace Example.Shared
{
public static class SharedGlobals
{
#if BLAZOR_SERVERSIDE
public static readonly bool IsBlazorServerSide = true;
public const string BlazorHostingMode = "SERVER-SIDE";
#else
public static readonly bool IsBlazorServerSide = false;
public const string BlazorHostingMode = "CLIENT-SIDE";
#endif // BLAZOR_SERVERSIDE
}
}
| 29.769231
| 63
| 0.718346
|
[
"MIT"
] |
ebekker/conjure-mvp
|
src/Example.Shared/SharedGlobals.cs
| 387
|
C#
|
namespace PersonalFinance.Authorization.Accounts.Dto
{
public class IsTenantAvailableOutput
{
public TenantAvailabilityState State { get; set; }
public int? TenantId { get; set; }
public IsTenantAvailableOutput()
{
}
public IsTenantAvailableOutput(TenantAvailabilityState state, int? tenantId = null)
{
State = state;
TenantId = tenantId;
}
}
}
| 22.4
| 91
| 0.607143
|
[
"MIT"
] |
Jfontenla/PersonalFinance
|
aspnet-core/src/PersonalFinance.Application/Authorization/Accounts/Dto/IsTenantAvailableOutput.cs
| 448
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ThriftS.Client.Pool
{
/// <summary>
/// Class ConnectionPoolManager.
/// </summary>
internal static class ConnectionPoolManager
{
/// <summary>
/// The pools
/// </summary>
private static readonly Dictionary<ConnectionSettingInfo, ConnectionPool> Pools = new Dictionary<ConnectionSettingInfo, ConnectionPool>();
/// <summary>
/// Gets the pool.
/// </summary>
/// <param name="host">The host.</param>
/// <param name="port">The port.</param>
/// <param name="timeout">The timeout.</param>
/// <returns>ConnectionPool.</returns>
public static ConnectionPool GetPool(string host, int port, int timeout)
{
var connection = new ConnectionSettingInfo(host, port, timeout);
if (Pools.ContainsKey(connection) == false)
{
lock (Pools)
{
if (Pools.ContainsKey(connection) == false)
{
Pools.Add(connection, new ConnectionPool(connection));
}
}
}
return Pools[connection];
}
}
}
| 29.477273
| 146
| 0.542791
|
[
"Apache-2.0"
] |
ZeemanHuang/ThriftS
|
thrifts-dotnet/ThriftS.Client/Pool/ConnectionPoolManager.cs
| 1,299
|
C#
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerCameraInitialPosition : MonoBehaviour {
public GameObject anchorTo;
private float xOffset = 0;
private float yOffset = 0;
private float zOffset = 0;
private Vector3 scale = new Vector3(1f, 1f, 1f);
// Use this for initialization
void Start()
{
Vector3 anchorPos = anchorTo.transform.position;
Vector3 offsets = new Vector3(xOffset, yOffset, zOffset);
Quaternion temp = new Quaternion();
anchorPos += offsets; // add offsets to the anchors pos
transform.localScale = scale;
transform.SetPositionAndRotation(anchorPos, temp);
}
}
| 24.793103
| 65
| 0.684284
|
[
"Unlicense"
] |
KristopherMoore/Midnight-The-Final-Sun
|
Assets/Scripts/Camera System/PlayerCameraInitialPosition.cs
| 721
|
C#
|
using System;
using System.Collections.Generic;
using Orchard.ContentManagement;
namespace Orchard.Tags.Models {
public class TagsPart : ContentPart<TagsPartRecord> {
public IEnumerable<string> CurrentTags {
get { return ParseTags(Retrieve<string>("CurrentTags")); }
set { Store("CurrentTags", String.Join(",", value)); }
}
private IEnumerable<string> ParseTags(string tags) {
return (tags ?? "").Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
}
}
}
| 33.8125
| 92
| 0.641405
|
[
"BSD-3-Clause"
] |
1996dylanriley/Orchard
|
src/Orchard.Web/Modules/Orchard.Tags/Models/TagsPart.cs
| 541
|
C#
|
using System;
namespace Trrntzip
{
[Flags]
public enum TrrntZipStatus
{
Unknown = 0,
ValidTrrntzip = 1,
CorruptZip = 2,
NotTrrntzipped = 4,
BadDirectorySeparator = 8,
Unsorted = 16,
ExtraDirectoryEnteries = 32,
RepeatFilesFound = 64
}
}
| 19.647059
| 37
| 0.535928
|
[
"MIT"
] |
eingrossfilou/RVWorld
|
Trrntzip/TrrntZipStatus.cs
| 336
|
C#
|
using System.ComponentModel.DataAnnotations;
namespace DETOWN.Infra.CrossCutting.Identity.Models.AccountViewModels
{
public class LoginWith2faViewModel
{
[Required]
[StringLength(7, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)]
[DataType(DataType.Text)]
[Display(Name = "Authenticator code")]
public string TwoFactorCode { get; set; }
[Display(Name = "Remember this machine")]
public bool RememberMachine { get; set; }
public bool RememberMe { get; set; }
}
}
| 31.157895
| 123
| 0.657095
|
[
"MIT"
] |
paulogabrielfs/DETOWN-API
|
src/DETOWN.Infra.CrossCutting.Identity/Models/AccountViewModels/LoginWith2faViewModel.cs
| 592
|
C#
|
using System;
using System.Collections.Generic;
using PlayMyLanguage.Processors.Support;
namespace PlayMyLanguage.Translation.Support
{
public interface ITextTranslator
{
/// <summary>
/// Reports when the translation status has changed.
/// </summary>
event EventHandler<StatusEventArgs> ProgressChanged;
/// <summary>
/// Translates texts from the <param name="source"></param> language to the <param name="target"></param> language.
/// </summary>
/// <param name="translatables">Texts to be translated.</param>
/// <param name="source">Source language.</param>
/// <param name="target">Target language.</param>
/// <returns></returns>
Translation Translate(IEnumerable<string> translatables, Language source, Language target);
}
}
| 36.73913
| 123
| 0.653254
|
[
"MIT"
] |
tasadar2/PlayMyLanguage
|
PlayMyLanguage/Translation/Support/ITextTranslator.cs
| 847
|
C#
|
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Bson;
namespace Catalog.API.Entites
{
public class Product
{
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
public string Name { get; set; }
public string Category { get; set; }
public string Summary { get; set; }
public string Description { get; set; }
public string ImageFile { get; set; }
public decimal Price { get; set; }
}
}
| 25.947368
| 47
| 0.62069
|
[
"MIT"
] |
santoshnarayanan/ASPNETMicroservices
|
src/Services/Catalog/Catalog.API/Entites/Product.cs
| 495
|
C#
|
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Sound.cs" company="Hämmer Electronics">
// Copyright (c) All rights reserved.
// </copyright>
// <summary>
// This class contains the sound attributes of the <see cref="MessageResult" />.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace SensorsPayloadDecoder.Elsys.ErsEye
{
/// <summary>
/// This class contains the sound attributes of the <see cref="MessageResult" />.
/// </summary>
public class Sound
{
/// <summary>
/// Gets or sets the sound average value.
/// </summary>
public int? SoundAverage { get; set; }
/// <summary>
/// Gets or sets the sound peak value.
/// </summary>
public int? SoundPeak { get; set; }
}
}
| 35.740741
| 120
| 0.436269
|
[
"MIT"
] |
SeppPenner/SensorsPayloadDecoder
|
src/SensorsPayloadDecoder.Elsys.ErsEye/Sound.cs
| 968
|
C#
|
using System;
namespace ExamKing.WebApp.Student
{
/// <summary>
/// 考试成绩输出
/// </summary>
public class StuscoreOutput
{
/// <summary>
/// ID
/// </summary>
public uint Id { get; set; }
/// <summary>
/// 学生ID
/// </summary>
public int StuId { get; set; }
/// <summary>
/// 课程ID
/// </summary>
public int CourseId { get; set; }
/// <summary>
/// 考试ID
/// </summary>
public int ExamId { get; set; }
/// <summary>
/// 考试成绩
/// </summary>
public int Score { get; set; }
/// <summary>
/// 创建时间
/// </summary>
public DateTimeOffset CreateTime { get; set; }
/// <summary>
/// 考试
/// </summary>
public ExamSubOoutput Exam { get; set; }
}
}
| 22.2
| 54
| 0.423423
|
[
"MIT"
] |
pig0224/ExamKing
|
ExamKing.WebApp.Student/Dtos/Output/StuscoreOutput.cs
| 932
|
C#
|
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Text;
namespace Newtonsoft.Json
{
/// <summary>
/// The exception thrown when an error occurs while reading Json text.
/// </summary>
#if !(SILVERLIGHT || WINDOWS_PHONE || NETFX_CORE || PORTABLE)
[Serializable]
#endif
public class JsonWriterException : JsonException
{
/// <summary>
/// Initializes a new instance of the <see cref="JsonWriterException"/> class.
/// </summary>
public JsonWriterException()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonWriterException"/> class
/// with a specified error message.
/// </summary>
/// <param name="message">The error message that explains the reason for the exception.</param>
public JsonWriterException(string message)
: base(message)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonWriterException"/> class
/// with a specified error message and a reference to the inner exception that is the cause of this exception.
/// </summary>
/// <param name="message">The error message that explains the reason for the exception.</param>
/// <param name="innerException">The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no inner exception is specified.</param>
public JsonWriterException(string message, Exception innerException)
: base(message, innerException)
{
}
#if !(WINDOWS_PHONE || SILVERLIGHT || NETFX_CORE || PORTABLE)
/// <summary>
/// Initializes a new instance of the <see cref="JsonWriterException"/> class.
/// </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>
public JsonWriterException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
#endif
}
}
| 44.771084
| 185
| 0.70479
|
[
"MIT"
] |
borewik/SteamBot
|
lib/JSON Library/Newtonsoft.Json/JsonWriterException.cs
| 3,716
|
C#
|
// <auto-generated>
// This file was generated by a tool; you should avoid making direct changes.
// Consider using 'partial classes' to extend these types
// Input: reader_base.proto
// </auto-generated>
#region Designer generated code
#pragma warning disable CS0612, CS0618, CS1591, CS3021, IDE0079, IDE1006, RCS1036, RCS1057, RCS1085, RCS1192
namespace Tensorflow
{
[global::ProtoBuf.ProtoContract()]
public partial class ReaderBaseState : global::ProtoBuf.IExtensible
{
private global::ProtoBuf.IExtension __pbn__extensionData;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
=> global::ProtoBuf.Extensible.GetExtensionObject(ref __pbn__extensionData, createIfMissing);
[global::ProtoBuf.ProtoMember(1, Name = @"work_started")]
public long WorkStarted { get; set; }
[global::ProtoBuf.ProtoMember(2, Name = @"work_finished")]
public long WorkFinished { get; set; }
[global::ProtoBuf.ProtoMember(3, Name = @"num_records_produced")]
public long NumRecordsProduced { get; set; }
[global::ProtoBuf.ProtoMember(4, Name = @"current_work")]
public byte[] CurrentWork { get; set; }
}
}
#pragma warning restore CS0612, CS0618, CS1591, CS3021, IDE0079, IDE1006, RCS1036, RCS1057, RCS1085, RCS1192
#endregion
| 37.135135
| 108
| 0.708879
|
[
"MIT"
] |
wxinix/TensorFlow-Island
|
Src/OpGenerator/ProtoGenFiles/r2.4.1/reader_base.cs
| 1,374
|
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("Semaphore.UI")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Semaphore.UI")]
[assembly: AssemblyCopyright("Copyright © 2019")]
[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("6924d829-57ac-42fd-aec2-5d2c26407d14")]
// 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.621622
| 84
| 0.746408
|
[
"Apache-2.0"
] |
mecvillarina/Semaphore-Client
|
Semaphore.UI/Properties/AssemblyInfo.cs
| 1,395
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Xunit.Abstractions;
namespace Xunit.Sdk
{
/// <summary>
/// Reflection-based implementation of <see cref="IReflectionTypeInfo"/>.
/// </summary>
public class ReflectionTypeInfo : LongLivedMarshalByRefObject, IReflectionTypeInfo
{
/// <summary>
/// Initializes a new instance of the <see cref="ReflectionTypeInfo"/> class.
/// </summary>
/// <param name="type">The type to wrap.</param>
public ReflectionTypeInfo(Type type)
{
Type = type;
}
/// <inheritdoc/>
public IAssemblyInfo Assembly
{
get { return Reflector.Wrap(Type.GetTypeInfo().Assembly); }
}
/// <inheritdoc/>
public ITypeInfo BaseType
{
get { return Reflector.Wrap(Type.GetTypeInfo().BaseType); }
}
/// <inheritdoc/>
public IEnumerable<ITypeInfo> Interfaces
{
get { return Type.GetTypeInfo().ImplementedInterfaces.Select(Reflector.Wrap).Cast<ITypeInfo>().ToList(); }
}
/// <inheritdoc/>
public bool IsAbstract
{
get { return Type.GetTypeInfo().IsAbstract; }
}
/// <inheritdoc/>
public bool IsGenericParameter
{
get { return Type.IsGenericParameter; }
}
/// <inheritdoc/>
public bool IsGenericType
{
get { return Type.GetTypeInfo().IsGenericType; }
}
/// <inheritdoc/>
public bool IsSealed
{
get { return Type.GetTypeInfo().IsSealed; }
}
/// <inheritdoc/>
public bool IsValueType
{
get { return Type.GetTypeInfo().IsValueType; }
}
/// <inheritdoc/>
public string Name
{
get { return Type.FullName ?? Type.Name; }
}
/// <inheritdoc/>
public Type Type { get; private set; }
/// <inheritdoc/>
public IEnumerable<IAttributeInfo> GetCustomAttributes(string assemblyQualifiedAttributeTypeName)
{
return ReflectionAttributeInfo.GetCustomAttributes(Type, assemblyQualifiedAttributeTypeName).ToList();
}
/// <inheritdoc/>
public IEnumerable<ITypeInfo> GetGenericArguments()
{
return Type.GetTypeInfo().GenericTypeArguments
.Select(Reflector.Wrap)
.ToList();
}
/// <inheritdoc/>
public IMethodInfo GetMethod(string methodName, bool includePrivateMethod)
{
var method = Type.GetRuntimeMethods()
.FirstOrDefault(m => (includePrivateMethod || m.IsPublic && m.DeclaringType != typeof(object)) && m.Name == methodName);
if (method == null)
return null;
return Reflector.Wrap(method);
}
/// <inheritdoc/>
public IEnumerable<IMethodInfo> GetMethods(bool includePrivateMethods)
{
return Type.GetRuntimeMethods().Where(m => includePrivateMethods || m.IsPublic)
.Select(Reflector.Wrap)
.Cast<IMethodInfo>()
.ToList();
}
/// <inheritdoc/>
public override string ToString()
{
return Type.ToString();
}
}
}
| 28.891667
| 149
| 0.547159
|
[
"Apache-2.0"
] |
remcomulder/xunit
|
src/xunit.execution/Sdk/Reflection/ReflectionTypeInfo.cs
| 3,469
|
C#
|
/*******************************************************************************
* Copyright 2012-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file.
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
* *****************************************************************************
*
* AWS Tools for Windows (TM) PowerShell (TM)
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using System.Text;
using Amazon.PowerShell.Common;
using Amazon.Runtime;
using Amazon.Shield;
using Amazon.Shield.Model;
namespace Amazon.PowerShell.Cmdlets.SHLD
{
/// <summary>
/// Authorizes the DDoS Response Team (DRT) to access the specified Amazon S3 bucket containing
/// your AWS WAF logs. You can associate up to 10 Amazon S3 buckets with your subscription.
///
///
/// <para>
/// To use the services of the DRT and make an <code>AssociateDRTLogBucket</code> request,
/// you must be subscribed to the <a href="https://aws.amazon.com/premiumsupport/business-support/">Business
/// Support plan</a> or the <a href="https://aws.amazon.com/premiumsupport/enterprise-support/">Enterprise
/// Support plan</a>.
/// </para>
/// </summary>
[Cmdlet("Grant", "SHLDDRTLogBucketAssociation", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.Medium)]
[OutputType("None")]
[AWSCmdlet("Calls the AWS Shield AssociateDRTLogBucket API operation.", Operation = new[] {"AssociateDRTLogBucket"}, SelectReturnType = typeof(Amazon.Shield.Model.AssociateDRTLogBucketResponse))]
[AWSCmdletOutput("None or Amazon.Shield.Model.AssociateDRTLogBucketResponse",
"This cmdlet does not generate any output." +
"The service response (type Amazon.Shield.Model.AssociateDRTLogBucketResponse) can be referenced from properties attached to the cmdlet entry in the $AWSHistory stack."
)]
public partial class GrantSHLDDRTLogBucketAssociationCmdlet : AmazonShieldClientCmdlet, IExecutor
{
#region Parameter LogBucket
/// <summary>
/// <para>
/// <para>The Amazon S3 bucket that contains your AWS WAF logs.</para>
/// </para>
/// </summary>
#if !MODULAR
[System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true)]
#else
[System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true, Mandatory = true)]
[System.Management.Automation.AllowEmptyString]
[System.Management.Automation.AllowNull]
#endif
[Amazon.PowerShell.Common.AWSRequiredParameter]
public System.String LogBucket { get; set; }
#endregion
#region Parameter Select
/// <summary>
/// Use the -Select parameter to control the cmdlet output. The cmdlet doesn't have a return value by default.
/// Specifying -Select '*' will result in the cmdlet returning the whole service response (Amazon.Shield.Model.AssociateDRTLogBucketResponse).
/// Specifying -Select '^ParameterName' will result in the cmdlet returning the selected cmdlet parameter value.
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public string Select { get; set; } = "*";
#endregion
#region Parameter PassThru
/// <summary>
/// Changes the cmdlet behavior to return the value passed to the LogBucket parameter.
/// The -PassThru parameter is deprecated, use -Select '^LogBucket' instead. This parameter will be removed in a future version.
/// </summary>
[System.Obsolete("The -PassThru parameter is deprecated, use -Select '^LogBucket' instead. This parameter will be removed in a future version.")]
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public SwitchParameter PassThru { get; set; }
#endregion
#region Parameter Force
/// <summary>
/// This parameter overrides confirmation prompts to force
/// the cmdlet to continue its operation. This parameter should always
/// be used with caution.
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public SwitchParameter Force { get; set; }
#endregion
protected override void ProcessRecord()
{
base.ProcessRecord();
var resourceIdentifiersText = FormatParameterValuesForConfirmationMsg(nameof(this.LogBucket), MyInvocation.BoundParameters);
if (!ConfirmShouldProceed(this.Force.IsPresent, resourceIdentifiersText, "Grant-SHLDDRTLogBucketAssociation (AssociateDRTLogBucket)"))
{
return;
}
var context = new CmdletContext();
// allow for manipulation of parameters prior to loading into context
PreExecutionContextLoad(context);
#pragma warning disable CS0618, CS0612 //A class member was marked with the Obsolete attribute
if (ParameterWasBound(nameof(this.Select)))
{
context.Select = CreateSelectDelegate<Amazon.Shield.Model.AssociateDRTLogBucketResponse, GrantSHLDDRTLogBucketAssociationCmdlet>(Select) ??
throw new System.ArgumentException("Invalid value for -Select parameter.", nameof(this.Select));
if (this.PassThru.IsPresent)
{
throw new System.ArgumentException("-PassThru cannot be used when -Select is specified.", nameof(this.Select));
}
}
else if (this.PassThru.IsPresent)
{
context.Select = (response, cmdlet) => this.LogBucket;
}
#pragma warning restore CS0618, CS0612 //A class member was marked with the Obsolete attribute
context.LogBucket = this.LogBucket;
#if MODULAR
if (this.LogBucket == null && ParameterWasBound(nameof(this.LogBucket)))
{
WriteWarning("You are passing $null as a value for parameter LogBucket which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues.");
}
#endif
// allow further manipulation of loaded context prior to processing
PostExecutionContextLoad(context);
var output = Execute(context) as CmdletOutput;
ProcessOutput(output);
}
#region IExecutor Members
public object Execute(ExecutorContext context)
{
var cmdletContext = context as CmdletContext;
// create request
var request = new Amazon.Shield.Model.AssociateDRTLogBucketRequest();
if (cmdletContext.LogBucket != null)
{
request.LogBucket = cmdletContext.LogBucket;
}
CmdletOutput output;
// issue call
var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint);
try
{
var response = CallAWSServiceOperation(client, request);
object pipelineOutput = null;
pipelineOutput = cmdletContext.Select(response, this);
output = new CmdletOutput
{
PipelineOutput = pipelineOutput,
ServiceResponse = response
};
}
catch (Exception e)
{
output = new CmdletOutput { ErrorResponse = e };
}
return output;
}
public ExecutorContext CreateContext()
{
return new CmdletContext();
}
#endregion
#region AWS Service Operation Call
private Amazon.Shield.Model.AssociateDRTLogBucketResponse CallAWSServiceOperation(IAmazonShield client, Amazon.Shield.Model.AssociateDRTLogBucketRequest request)
{
Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "AWS Shield", "AssociateDRTLogBucket");
try
{
#if DESKTOP
return client.AssociateDRTLogBucket(request);
#elif CORECLR
return client.AssociateDRTLogBucketAsync(request).GetAwaiter().GetResult();
#else
#error "Unknown build edition"
#endif
}
catch (AmazonServiceException exc)
{
var webException = exc.InnerException as System.Net.WebException;
if (webException != null)
{
throw new Exception(Utils.Common.FormatNameResolutionFailureMessage(client.Config, webException.Message), webException);
}
throw;
}
}
#endregion
internal partial class CmdletContext : ExecutorContext
{
public System.String LogBucket { get; set; }
public System.Func<Amazon.Shield.Model.AssociateDRTLogBucketResponse, GrantSHLDDRTLogBucketAssociationCmdlet, object> Select { get; set; } =
(response, cmdlet) => null;
}
}
}
| 45.191964
| 280
| 0.615331
|
[
"Apache-2.0"
] |
QPC-database/aws-tools-for-powershell
|
modules/AWSPowerShell/Cmdlets/Shield/Basic/Grant-SHLDDRTLogBucketAssociation-Cmdlet.cs
| 10,123
|
C#
|
using System;
using System.Text;
using NpuRozklad.Core.Entities;
namespace NpuRozklad.Telegram.Helpers
{
internal static class TimetableFacultyGroupViewMenuCallbackDataSerializer
{
internal static string ToCallbackData(bool isNextWeek, DayOfWeek dayOfWeek, Group facultyGroup)
{
var builder = new StringBuilder();
builder.AppendWithSeparator(
CallbackDataFormatter.ToCallBackData(CallbackQueryActionType.ShowTimetableFacultyGroupViewMenu));
builder.AppendWithSeparator(isNextWeek ? "1" : "0");
builder.AppendWithSeparator(((int) dayOfWeek).ToString());
builder.AppendWithSeparator(
CallbackDataFormatter.ToCallBackData(facultyGroup));
return builder.ToString();
}
}
}
| 35.217391
| 113
| 0.692593
|
[
"MIT"
] |
matryosha/Npu-Rozklad-App
|
Src/NpuRozklad.Telegram/Helpers/CallbackDataSerializers.cs
| 810
|
C#
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using Microsoft.MixedReality.Toolkit.Input;
using System;
/// <summary>
/// Interface defining a mouse input device manager.
/// </summary>
public interface IMixedRealityMouseDeviceManager : IMixedRealityInputDeviceManager
{
/// <summary>
/// Typed representation of the ConfigurationProfile property.
/// </summary>
[ObsoleteAttribute("The MouseInputProfile property has been deprecated and will be removed in a future version of MRTK.")]
MixedRealityMouseInputProfile MouseInputProfile { get; }
/// <summary>
/// Gets or sets a multiplier value used to adjust the speed of the mouse cursor.
/// </summary>
float CursorSpeed { get; set; }
/// <summary>
/// Gets or sets a multiplier value used to adjust the speed of the mouse wheel.
/// </summary>
float WheelSpeed { get; set; }
}
| 36.571429
| 127
| 0.693359
|
[
"MIT"
] |
Danny041291/Create-Your-First-HoloLens-Application-Using-Mixed-Reality-Toolkit
|
Assets/MixedRealityToolkit/Interfaces/InputSystem/IMixedRealityMouseDeviceManager.cs
| 1,026
|
C#
|
using Xunit;
using System.Collections.Generic;
using System;
using System.Data;
using System.Data.SqlClient;
namespace HairSalon
{
[Collection("HairSalonTests")]
public class ClientTest : IDisposable
{
public ClientTest()
{
DBConfiguration.ConnectionString = "Data Source=(localdb)\\mssqllocaldb;Initial Catalog=hair_salon_test;Integrated Security=SSPI;";
}
[Fact]
public void Test_DatabaseEmptyAtFirst()
{
int result = Client.GetAll().Count;
Assert.Equal(0, result);
}
[Fact]
public void Test_Equal_ReturnsTrueIfNamesAreTheSame()
{
Client firstClient = new Client("Person1", 1, "email");
Client secondClient = new Client("Person1", 1, "email");
Assert.Equal(firstClient, secondClient);
}
[Fact]
public void Test_Save_SavesToDatabase()
{
Client testClient = new Client("Person1", 1, "email");
testClient.Save();
List<Client> result = Client.GetAll();
List<Client> testList = new List<Client>{testClient};
Assert.Equal(testList, result);
}
[Fact]
public void Test_Save_AssignsIdToObject()
{
Client testClient = new Client("Person1", 1, "email");
testClient.Save();
Client savedClient = Client.GetAll()[0];
int result = savedClient.GetId();
int testId = testClient.GetId();
Assert.Equal(testId, result);
}
[Fact]
public void Test_Find_FindsClientInDatabase()
{
Client testClient = new Client("Pesron1", 1, "email");
testClient.Save();
Client foundClient = Client.Find(testClient.GetId());
Assert.Equal(testClient, foundClient);
}
// [Fact]
// public void Test_ByStylist_ReturnsTrueIfListsAreTheSame()
// {
// Stylist newStylist = new Stylist("A", "a@a.com", "photolink");
// Client firstClient = new Client("Person A", 1, "email", newStylist.GetId());
// Client secondClient = new Client("Person B", 2, "email", newStylist.GetId());
// newStylist.Save();
// firstClient.Save();
// secondClient.Save();
// List<Client> result = Client.ByStylist();
// List<Client> testList = new List<Client>{firstClient, secondClient};
// Assert.Equal(testList, result);
// }
public void Dispose()
{
Client.DeleteAll();
}
}
}
| 25.966667
| 137
| 0.63543
|
[
"MIT"
] |
aglines-epicodus/csharp-week3-project
|
Tests/ClientTest.cs
| 2,337
|
C#
|
namespace CoreHook.BinaryInjection.Loader
{
public class HostArguments : IHostArguments
{
public bool Verbose { get; set; }
public string PayloadFileName { get; set; }
public string CoreRootPath { get; set; }
}
}
| 25
| 51
| 0.648
|
[
"MIT"
] |
abc-wizard/CoreHook
|
src/CoreHook.BinaryInjection/Loader/HostArguments.cs
| 252
|
C#
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using Azure.Core.TestFramework;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Azure.AI.TextAnalytics.Samples
{
[LiveOnly]
public partial class TextAnalyticsSamples
{
[Test]
public async Task ExtractEntityLinkingBatchAsync()
{
string endpoint = TestEnvironment.Endpoint;
string apiKey = TestEnvironment.ApiKey;
// Instantiate a client that will be used to call the service.
var client = new TextAnalyticsClient(new Uri(endpoint), new AzureKeyCredential(apiKey));
var documents = new List<TextDocumentInput>
{
new TextDocumentInput("1", "Microsoft was founded by Bill Gates and Paul Allen.")
{
Language = "en",
},
new TextDocumentInput("2", "Text Analytics is one of the Azure Cognitive Services.")
{
Language = "en",
},
new TextDocumentInput("3", "Pike place market is my favorite Seattle attraction.")
{
Language = "en",
}
};
RecognizeLinkedEntitiesResultCollection results = await client.RecognizeLinkedEntitiesBatchAsync(documents, new TextAnalyticsRequestOptions { IncludeStatistics = true });
int i = 0;
Console.WriteLine($"Results of Azure Text Analytics \"Entity Linking\", version: \"{results.ModelVersion}\"");
Console.WriteLine("");
foreach (RecognizeLinkedEntitiesResult result in results)
{
TextDocumentInput document = documents[i++];
Console.WriteLine($"On document (Id={document.Id}, Language=\"{document.Language}\", Text=\"{document.Text}\"):");
if (result.HasError)
{
Console.WriteLine($" Document error code: {result.Error.Code}.");
Console.WriteLine($" Message: {result.Error.Message}.");
}
else
{
Console.WriteLine($" Extracted the following {result.Entities.Count()} linked entities:");
foreach (LinkedEntity linkedEntity in result.Entities)
{
Console.WriteLine($" Name: \"{linkedEntity.Name}\", Language: {linkedEntity.Language}, Data Source: {linkedEntity.DataSource}, Url: {linkedEntity.Url.ToString()}, Entity Id in Data Source: \"{linkedEntity.DataSourceEntityId}\"");
foreach (LinkedEntityMatch match in linkedEntity.Matches)
{
Console.WriteLine($" Match Text: \"{match.Text}\", Confidence score: {match.ConfidenceScore}");
}
}
Console.WriteLine($" Document statistics:");
Console.WriteLine($" Character count (in Unicode graphemes): {result.Statistics.CharacterCount}");
Console.WriteLine($" Transaction count: {result.Statistics.TransactionCount}");
Console.WriteLine("");
}
}
Console.WriteLine($"Batch operation statistics:");
Console.WriteLine($" Document count: {results.Statistics.DocumentCount}");
Console.WriteLine($" Valid document count: {results.Statistics.ValidDocumentCount}");
Console.WriteLine($" Invalid document count: {results.Statistics.InvalidDocumentCount}");
Console.WriteLine($" Transaction count: {results.Statistics.TransactionCount}");
Console.WriteLine("");
}
}
}
| 44.896552
| 256
| 0.570405
|
[
"MIT"
] |
LTA-Thinking/azure-sdk-for-net
|
sdk/textanalytics/Azure.AI.TextAnalytics/tests/samples/Sample6_RecognizeLinkedEntitiesBatchAsync.cs
| 3,908
|
C#
|
#if USE_UNI_LUA
using LuaAPI = UniLua.Lua;
using RealStatePtr = UniLua.ILuaState;
using LuaCSFunction = UniLua.CSharpFunctionDelegate;
#else
using LuaAPI = XLua.LuaDLL.Lua;
using RealStatePtr = System.IntPtr;
using LuaCSFunction = XLua.LuaDLL.lua_CSFunction;
#endif
using XLua;
using System.Collections.Generic;
using Spine.Unity.Modules.AttachmentTools;
namespace XLua.CSObjectWrap
{
using Utils = XLua.Utils;
public class SpinePathAttachmentWrap
{
public static void __Register(RealStatePtr L)
{
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
System.Type type = typeof(Spine.PathAttachment);
Utils.BeginObjectRegister(type, L, translator, 0, 1, 3, 3);
Utils.RegisterFunc(L, Utils.METHOD_IDX, "GetClone", _m_GetClone);
Utils.RegisterFunc(L, Utils.GETTER_IDX, "Lengths", _g_get_Lengths);
Utils.RegisterFunc(L, Utils.GETTER_IDX, "Closed", _g_get_Closed);
Utils.RegisterFunc(L, Utils.GETTER_IDX, "ConstantSpeed", _g_get_ConstantSpeed);
Utils.RegisterFunc(L, Utils.SETTER_IDX, "Lengths", _s_set_Lengths);
Utils.RegisterFunc(L, Utils.SETTER_IDX, "Closed", _s_set_Closed);
Utils.RegisterFunc(L, Utils.SETTER_IDX, "ConstantSpeed", _s_set_ConstantSpeed);
Utils.EndObjectRegister(type, L, translator, null, null,
null, null, null);
Utils.BeginClassRegister(type, L, __CreateInstance, 1, 0, 0);
Utils.EndClassRegister(type, L, translator);
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int __CreateInstance(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
if(LuaAPI.lua_gettop(L) == 2 && (LuaAPI.lua_isnil(L, 2) || LuaAPI.lua_type(L, 2) == LuaTypes.LUA_TSTRING))
{
string _name = LuaAPI.lua_tostring(L, 2);
Spine.PathAttachment gen_ret = new Spine.PathAttachment(_name);
translator.Push(L, gen_ret);
return 1;
}
}
catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return LuaAPI.luaL_error(L, "invalid arguments to Spine.PathAttachment constructor!");
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _m_GetClone(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
Spine.PathAttachment gen_to_be_invoked = (Spine.PathAttachment)translator.FastGetCSObj(L, 1);
{
Spine.PathAttachment gen_ret = gen_to_be_invoked.GetClone( );
translator.Push(L, gen_ret);
return 1;
}
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _g_get_Lengths(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
Spine.PathAttachment gen_to_be_invoked = (Spine.PathAttachment)translator.FastGetCSObj(L, 1);
translator.Push(L, gen_to_be_invoked.Lengths);
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return 1;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _g_get_Closed(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
Spine.PathAttachment gen_to_be_invoked = (Spine.PathAttachment)translator.FastGetCSObj(L, 1);
LuaAPI.lua_pushboolean(L, gen_to_be_invoked.Closed);
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return 1;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _g_get_ConstantSpeed(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
Spine.PathAttachment gen_to_be_invoked = (Spine.PathAttachment)translator.FastGetCSObj(L, 1);
LuaAPI.lua_pushboolean(L, gen_to_be_invoked.ConstantSpeed);
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return 1;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _s_set_Lengths(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
Spine.PathAttachment gen_to_be_invoked = (Spine.PathAttachment)translator.FastGetCSObj(L, 1);
gen_to_be_invoked.Lengths = (float[])translator.GetObject(L, 2, typeof(float[]));
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return 0;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _s_set_Closed(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
Spine.PathAttachment gen_to_be_invoked = (Spine.PathAttachment)translator.FastGetCSObj(L, 1);
gen_to_be_invoked.Closed = LuaAPI.lua_toboolean(L, 2);
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return 0;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _s_set_ConstantSpeed(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
Spine.PathAttachment gen_to_be_invoked = (Spine.PathAttachment)translator.FastGetCSObj(L, 1);
gen_to_be_invoked.ConstantSpeed = LuaAPI.lua_toboolean(L, 2);
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return 0;
}
}
}
| 33.033654
| 110
| 0.579246
|
[
"BSD-3-Clause"
] |
doupihule/gameDemo
|
Assets/XLua/Gen/SpinePathAttachmentWrap.cs
| 6,873
|
C#
|
using System;
namespace ExampleProject
{
public class DBTables
{
internal static readonly String USERS = "users";
internal static readonly String COUNT_USERS = "users_count";
internal static readonly String USERS_MATERIALIZED_VIEW = "users_mv";
}
}
| 21.214286
| 77
| 0.673401
|
[
"MIT"
] |
EntritGroup/db.cassandra.csharp.query-builder
|
samples/ExampleProject/DBTables.cs
| 299
|
C#
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Handelabra.Sentinels.Engine.Controller;
using Handelabra.Sentinels.Engine.Model;
namespace SotmWorkshop.Moonwolf
{
public class ForcedChangeCardController : MoonwolfCardController
{
public ForcedChangeCardController(Card card, TurnTakerController turnTakerController)
: base(card, turnTakerController)
{
SpecialStringMaker.ShowNumberOfCardsAtLocation(TurnTaker.Deck, new LinqCardCriteria(c => IsFeral(c), FeralKeyword));
}
public override IEnumerator Play()
{
//Moonwolf deals herself 2 Melee Damage.
IEnumerator coroutine = DealDamage(CharacterCard, CharacterCard, 2, DamageType.Melee, cardSource: GetCardSource());
if (base.UseUnityCoroutines)
{
yield return base.GameController.StartCoroutine(coroutine);
}
else
{
base.GameController.ExhaustCoroutine(coroutine);
}
//Search your deck for a Feral Card, and put the selected card into play or in your hand, then shuffle your deck.
coroutine = SearchForCards(DecisionMaker, true, false, 0, 1, new LinqCardCriteria(card => IsFeral(card), FeralKeyword), true, true, false, shuffleAfterwards: true);
if (base.UseUnityCoroutines)
{
yield return base.GameController.StartCoroutine(coroutine);
}
else
{
base.GameController.ExhaustCoroutine(coroutine);
}
}
}
}
| 39.071429
| 176
| 0.645338
|
[
"MIT"
] |
MSpekkio/SotmWorkshop
|
Moonwolf/Controllers/Cards/ForcedChangeCardController.cs
| 1,641
|
C#
|
using FluentAssertions;
using Xunit;
using Vaquinha.Domain;
using Vaquinha.Domain.Entities;
using System.Linq;
using Vaquinha.Tests.Common.Fixtures;
namespace Vaquinha.Unit.Tests.DomainTests
{
[Collection(nameof(PessoaFixtureCollection))]
public class DomainNotificationServiceTests: IClassFixture<PessoaFixture>
{
private readonly PessoaFixture _pessoaFixture;
private readonly IDomainNotificationService _domainNotificationService;
public DomainNotificationServiceTests(PessoaFixture fixture)
{
_pessoaFixture = fixture;
_domainNotificationService = new DomainNotificationService();
}
[Trait("DomainNotificationService", "DomainNotificationService_NovaClasse_NaoDevePossuirNotificacoes")]
[Fact]
public void DomainNotificationService_NovaClasse_NaoDevePossuirNotificacoes()
{
// Arrange & Act
var domainNotification = new DomainNotificationService();
// Assert
domainNotification.PossuiErros.Should().BeFalse(because:"ainda não foi adicionado nenhuma notificadao de dominino");
}
[Trait("DomainNotificationService", "DomainNotificationService_AdicionarNotificacao_HasNotificationsTrue")]
[Fact]
public void DomainNotificationService_AdicionarNotificacao_HasNotificationsTrue()
{
// Arrange
var domainNotification = new DomainNotification("RequiredField", "O campo Nome é obrigatório");
// Act
_domainNotificationService.Adicionar(domainNotification);
// Assert
_domainNotificationService.PossuiErros.Should().BeTrue(because: "foi adicionado a notificacao de codigo RequiredField");
var notifications = _domainNotificationService.RecuperarErrosDominio().Select(a => a.MensagemErro);
notifications.Should().Contain("O campo Nome é obrigatório", because: "foi adicionado a notificacao de codigo RequiredField");
}
[Trait("DomainNotificationService", "DomainNotificationService_AdicionarEntidade_HasNotificationsTrue")]
[Fact]
public void DomainNotificationService_AdicionarEntidade_HasNotificationsTrue()
{
// Arrange
var pessoa = _pessoaFixture.PessoaVazia();
pessoa.Valido();
// Act
_domainNotificationService.Adicionar(pessoa);
// Assert
var notifications = _domainNotificationService.RecuperarErrosDominio().Select(a => a.MensagemErro);
notifications.Should().HaveCount(2, because: "nenhum dos 2 campos obrigatórios foi informado.");
notifications.Should().Contain("O campo Nome é obrigatório.", because: "o campo Nome não foi informado.");
notifications.Should().Contain("O campo Email é obrigatório.", because: "o campo Email não foi informado.");
_domainNotificationService.PossuiErros.Should().BeTrue(because: "foi adicionado a entidade pessoa inválida");
}
}
}
| 44.338028
| 139
| 0.679161
|
[
"MIT"
] |
dayvidsonveiga/crowdfunding-dotnet-dio
|
tests/Vaquinha.Unit.Tests/DomainTests/DomainNotificationServiceTests.cs
| 3,163
|
C#
|
using Microsoft.VisualBasic.Devices;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;
namespace InstallC4
{
class Program
{
static void Main(string[] args)
{
if (args.Length >= 1)
{
if (!HasAdministratorPrivileges())
{
Console.Write("Access denied! Start command processor as administrator? (Y/n)");
ConsoleKey key = Console.ReadKey().Key;
if (key == ConsoleKey.Y || key == ConsoleKey.Enter)
{
ProcessStartInfo PSI = new ProcessStartInfo(Process.GetCurrentProcess().Parent().MainModule.FileName);
PSI.Verb = "runas";
Process.Start(PSI);
}
return;
}
if (args.Length >= 1 && Path.GetFullPath(args[0]) == Path.GetFullPath(@"C:\C4"))
{
try
{
if (Directory.Exists(@"C:\C4")) new Computer().FileSystem.DeleteDirectory(@"C:\C4", Microsoft.VisualBasic.FileIO.DeleteDirectoryOption.DeleteAllContents);
new Computer().FileSystem.CopyDirectory(@"C4", @"C:\C4");
try
{
if (!Environment.GetEnvironmentVariable("PATH", EnvironmentVariableTarget.Machine).Contains(@"C:\C4"))
{
Environment.SetEnvironmentVariable("PATH",
Environment.GetEnvironmentVariable("PATH",
EnvironmentVariableTarget.Machine) + @";C:\C4\bin;", EnvironmentVariableTarget.Machine);
}
}
catch { }
try
{
if (!Environment.GetEnvironmentVariable("PATH", EnvironmentVariableTarget.User).Contains(@"C:\C4"))
{
Environment.SetEnvironmentVariable("PATH",
Environment.GetEnvironmentVariable("PATH",
EnvironmentVariableTarget.User) + @";C:\C4\bin;", EnvironmentVariableTarget.User);
}
}
catch { }
}
catch { }
if (Directory.Exists(@"C:\C4\bin"))
{
SetFullControlPermissionsToEveryone(@"C:\C4\bin");
SetFullControlPermissionsToEveryone(@"C:\C4\src");
SetFullControlPermissionsToEveryone(@"C:\C4");
Console.WriteLine(@"Run C4 detonate to complete the installation.");
}
else
{
Console.WriteLine(@"The installation failed.");
}
}
else
{
Console.WriteLine(@"Sorry, but you must install to 'C:\C4'.");
}
}
else
{
Console.WriteLine(@"Invalid. Please run InstallC4 C:\C4 in your command processor.");
}
}
static void SetFullControlPermissionsToEveryone(string path)
{
const FileSystemRights rights = FileSystemRights.FullControl;
var allUsers = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null);
// Add Access Rule to the actual directory itself
var accessRule = new FileSystemAccessRule(
allUsers,
rights,
InheritanceFlags.None,
PropagationFlags.NoPropagateInherit,
AccessControlType.Allow);
var info = new DirectoryInfo(path);
var security = info.GetAccessControl(AccessControlSections.Access);
bool result;
security.ModifyAccessRule(AccessControlModification.Set, accessRule, out result);
if (!result)
{
throw new InvalidOperationException("Failed to give full-control permission to all users for path " + path);
}
// add inheritance
var inheritedAccessRule = new FileSystemAccessRule(
allUsers,
rights,
InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
PropagationFlags.InheritOnly,
AccessControlType.Allow);
bool inheritedResult;
security.ModifyAccessRule(AccessControlModification.Add, inheritedAccessRule, out inheritedResult);
if (!inheritedResult)
{
throw new InvalidOperationException("Failed to give full-control permission inheritance to all users for " + path);
}
info.SetAccessControl(security);
}
private static bool HasAdministratorPrivileges()
{
WindowsIdentity id = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(id);
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
}
public static class ProcessExtensions
{
private static string FindIndexedProcessName(int pid)
{
var processName = Process.GetProcessById(pid).ProcessName;
var processesByName = Process.GetProcessesByName(processName);
string processIndexdName = null;
for (var index = 0; index < processesByName.Length; index++)
{
processIndexdName = index == 0 ? processName : processName + "#" + index;
var processId = new PerformanceCounter("Process", "ID Process", processIndexdName);
if ((int)processId.NextValue() == pid)
{
return processIndexdName;
}
}
return processIndexdName;
}
private static Process FindPidFromIndexedProcessName(string indexedProcessName)
{
var parentId = new PerformanceCounter("Process", "Creating Process ID", indexedProcessName);
return Process.GetProcessById((int)parentId.NextValue());
}
public static Process Parent(this Process process)
{
return FindPidFromIndexedProcessName(FindIndexedProcessName(process.Id));
}
}
}
| 40.255952
| 178
| 0.526246
|
[
"MIT"
] |
TeddyTelanoff/C4-lang
|
C4/src/InstallC4/InstallC4/Program.cs
| 6,765
|
C#
|
using System.Threading.Tasks;
using IdentityServer4.Models;
using IdentityServer4.Validation;
namespace Host.Extensions
{
public class NoSubjectExtensionGrantValidator : IExtensionGrantValidator
{
public Task ValidateAsync(ExtensionGrantValidationContext context)
{
var credential = context.Request.Raw.Get("custom_credential");
if (credential != null)
{
context.Result = new GrantValidationResult();
}
else
{
// custom error message
context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, "invalid custom credential");
}
return Task.CompletedTask;
}
public string GrantType
{
get { return "custom.nosubject"; }
}
}
}
| 27.677419
| 121
| 0.600233
|
[
"Apache-2.0"
] |
DotNetUz/IdentityServer4.Nhibernate
|
src/Host/Extensions/NoSubjectExtensionGrantValidator.cs
| 860
|
C#
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
namespace LinqToDB.Linq.Builder
{
using Extensions;
using LinqToDB.Expressions;
using LinqToDB.Mapping;
class ExpressionTestGenerator
{
readonly bool _mangleNames;
readonly StringBuilder _exprBuilder = new ();
IDataContext? _dataContext;
string _indent = "\t\t\t\t";
public ExpressionTestGenerator(): this(true)
{
}
public ExpressionTestGenerator(bool mangleNames)
{
_mangleNames = mangleNames;
}
void PushIndent() { _indent += '\t'; }
void PopIndent () { _indent = _indent.Substring(1); }
readonly HashSet<Expression> _visitedExprs = new ();
private VisitFuncVisitor<ExpressionTestGenerator>? _buildExpressionVisitor;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void Build(Expression expr)
{
(_buildExpressionVisitor ??= VisitFuncVisitor<ExpressionTestGenerator>.Create(this, static (ctx, e) => ctx.BuildExpression(e))).Visit(expr);
}
bool BuildExpression(Expression expr)
{
switch (expr.NodeType)
{
case ExpressionType.Add:
case ExpressionType.AddChecked:
case ExpressionType.And:
case ExpressionType.AndAlso:
case ExpressionType.Assign:
case ExpressionType.Coalesce:
case ExpressionType.Divide:
case ExpressionType.Equal:
case ExpressionType.ExclusiveOr:
case ExpressionType.GreaterThan:
case ExpressionType.GreaterThanOrEqual:
case ExpressionType.LeftShift:
case ExpressionType.LessThan:
case ExpressionType.LessThanOrEqual:
case ExpressionType.Modulo:
case ExpressionType.Multiply:
case ExpressionType.MultiplyChecked:
case ExpressionType.NotEqual:
case ExpressionType.Or:
case ExpressionType.OrElse:
case ExpressionType.Power:
case ExpressionType.RightShift:
case ExpressionType.Subtract:
case ExpressionType.SubtractChecked:
{
var e = (BinaryExpression)expr;
_exprBuilder.Append('(');
Build(e.Left);
switch (expr.NodeType)
{
case ExpressionType.Add :
case ExpressionType.AddChecked : _exprBuilder.Append(" + "); break;
case ExpressionType.And : _exprBuilder.Append(" & "); break;
case ExpressionType.AndAlso : _exprBuilder.Append(" && "); break;
case ExpressionType.Assign : _exprBuilder.Append(" = "); break;
case ExpressionType.Coalesce : _exprBuilder.Append(" ?? "); break;
case ExpressionType.Divide : _exprBuilder.Append(" / "); break;
case ExpressionType.Equal : _exprBuilder.Append(" == "); break;
case ExpressionType.ExclusiveOr : _exprBuilder.Append(" ^ "); break;
case ExpressionType.GreaterThan : _exprBuilder.Append(" > "); break;
case ExpressionType.GreaterThanOrEqual : _exprBuilder.Append(" >= "); break;
case ExpressionType.LeftShift : _exprBuilder.Append(" << "); break;
case ExpressionType.LessThan : _exprBuilder.Append(" < "); break;
case ExpressionType.LessThanOrEqual : _exprBuilder.Append(" <= "); break;
case ExpressionType.Modulo : _exprBuilder.Append(" % "); break;
case ExpressionType.Multiply :
case ExpressionType.MultiplyChecked : _exprBuilder.Append(" * "); break;
case ExpressionType.NotEqual : _exprBuilder.Append(" != "); break;
case ExpressionType.Or : _exprBuilder.Append(" | "); break;
case ExpressionType.OrElse : _exprBuilder.Append(" || "); break;
case ExpressionType.Power : _exprBuilder.Append(" ** "); break;
case ExpressionType.RightShift : _exprBuilder.Append(" >> "); break;
case ExpressionType.Subtract :
case ExpressionType.SubtractChecked : _exprBuilder.Append(" - "); break;
}
Build(e.Right);
_exprBuilder.Append(')');
return false;
}
case ExpressionType.ArrayLength:
{
var e = (UnaryExpression)expr;
Build(e.Operand);
_exprBuilder.Append(".Length");
return false;
}
case ExpressionType.Convert:
case ExpressionType.ConvertChecked:
{
var e = (UnaryExpression)expr;
_exprBuilder.AppendFormat("({0})", GetTypeName(e.Type));
Build(e.Operand);
return false;
}
case ExpressionType.Negate:
case ExpressionType.NegateChecked:
{
_exprBuilder.Append('-');
return true;
}
case ExpressionType.Not:
{
_exprBuilder.Append('!');
return true;
}
case ExpressionType.Quote:
return true;
case ExpressionType.TypeAs:
{
var e = (UnaryExpression)expr;
_exprBuilder.Append('(');
Build(e.Operand);
_exprBuilder.AppendFormat(" as {0})", GetTypeName(e.Type));
return false;
}
case ExpressionType.UnaryPlus:
{
_exprBuilder.Append('+');
return true;
}
case ExpressionType.ArrayIndex:
{
var e = (BinaryExpression)expr;
Build(e.Left);
_exprBuilder.Append('[');
Build(e.Right);
_exprBuilder.Append(']');
return false;
}
case ExpressionType.MemberAccess :
{
var e = (MemberExpression)expr;
Build(e.Expression);
_exprBuilder.AppendFormat(".{0}", MangleName(e.Member.DeclaringType!, e.Member.Name, "P"));
return false;
}
case ExpressionType.Parameter :
{
var e = (ParameterExpression)expr;
_exprBuilder.Append(MangleName(e.Name, "p"));
return false;
}
case ExpressionType.Call :
{
var ex = (MethodCallExpression)expr;
var mi = ex.Method;
var attrs = mi.GetCustomAttributes(typeof(ExtensionAttribute), false);
if (attrs.Length != 0)
{
Build(ex.Arguments[0]);
PushIndent();
_exprBuilder.AppendLine().Append(_indent);
}
else if (ex.Object != null)
Build(ex.Object);
else
_exprBuilder.Append(GetTypeName(mi.DeclaringType!));
_exprBuilder.Append('.').Append(MangleName(mi.DeclaringType!, mi.Name, "M"));
if ((!ex.IsQueryable() || ex.Method.DeclaringType == typeof(DataExtensions))
&& mi.IsGenericMethod && mi.GetGenericArguments().Select(GetTypeName).All(t => t != null))
{
_exprBuilder
.Append('<')
.Append(GetTypeNames(mi.GetGenericArguments(), ","))
.Append('>');
}
_exprBuilder.Append('(');
PushIndent();
var n = attrs.Length != 0 ? 1 : 0;
for (var i = n; i < ex.Arguments.Count; i++)
{
if (i != n)
_exprBuilder.Append(',');
_exprBuilder.AppendLine().Append(_indent);
Build(ex.Arguments[i]);
}
PopIndent();
_exprBuilder.Append(')');
if (attrs.Length != 0)
{
PopIndent();
}
return false;
}
case ExpressionType.Constant:
{
var c = (ConstantExpression)expr;
if (c.Value is IQueryable queryable)
{
var e = queryable.Expression;
if (_visitedExprs.Add(e))
{
Build(e);
return false;
}
}
if (typeof(Table<>).IsSameOrParentOf(expr.Type))
_exprBuilder.AppendFormat("db.GetTable<{0}>()", GetTypeName(expr.Type.GetGenericArguments()[0]));
else if (c.Value == _dataContext)
_exprBuilder.Append("db");
else if (expr.ToString() == "value(" + expr.Type + ")")
_exprBuilder.Append("value(").Append(GetTypeName(expr.Type)).Append(')');
else
_exprBuilder.Append(expr);
return true;
}
case ExpressionType.Lambda:
{
var le = (LambdaExpression)expr;
var ps = string.Join(", ", le.Parameters.Select(p => MangleName(p.Name, "p")));
if (le.Parameters.Count == 1)
_exprBuilder.Append(ps);
else
_exprBuilder.Append('(').Append(ps).Append(')');
_exprBuilder.Append(" => ");
Build(le.Body);
return false;
}
case ExpressionType.Conditional:
{
var e = (ConditionalExpression)expr;
_exprBuilder.Append('(');
Build(e.Test);
_exprBuilder.Append(" ? ");
Build(e.IfTrue);
_exprBuilder.Append(" : ");
Build(e.IfFalse);
_exprBuilder.Append(')');
return false;
}
case ExpressionType.New:
{
var ne = (NewExpression)expr;
if (IsAnonymous(ne.Type))
{
if (ne.Members.Count == 1)
{
_exprBuilder.AppendFormat("new {{ {0} = ", MangleName(ne.Members[0].DeclaringType!, ne.Members[0].Name, "P"));
Build(ne.Arguments[0]);
_exprBuilder.Append(" }}");
}
else
{
_exprBuilder.AppendLine("new").Append(_indent).Append('{');
PushIndent();
for (var i = 0; i < ne.Members.Count; i++)
{
_exprBuilder.AppendLine().Append(_indent).AppendFormat("{0} = ", MangleName(ne.Members[i].DeclaringType!, ne.Members[i].Name, "P"));
Build(ne.Arguments[i]);
if (i + 1 < ne.Members.Count)
_exprBuilder.Append(',');
}
PopIndent();
_exprBuilder.AppendLine().Append(_indent).Append('}');
}
}
else
{
_exprBuilder.AppendFormat("new {0}(", GetTypeName(ne.Type));
for (var i = 0; i < ne.Arguments.Count; i++)
{
Build(ne.Arguments[i]);
if (i + 1 < ne.Arguments.Count)
_exprBuilder.Append(", ");
}
_exprBuilder.Append(')');
}
return false;
}
case ExpressionType.MemberInit:
{
void Modify(MemberBinding b)
{
switch (b.BindingType)
{
case MemberBindingType.Assignment:
var ma = (MemberAssignment) b;
_exprBuilder.AppendFormat("{0} = ", MangleName(ma.Member.DeclaringType!, ma.Member.Name, "P"));
Build(ma.Expression);
break;
default:
_exprBuilder.Append(b);
break;
}
}
var e = (MemberInitExpression)expr;
Build(e.NewExpression);
if (e.Bindings.Count == 1)
{
_exprBuilder.Append(" { ");
Modify(e.Bindings[0]);
_exprBuilder.Append(" }");
}
else
{
_exprBuilder.AppendLine().Append(_indent).Append('{');
PushIndent();
for (var i = 0; i < e.Bindings.Count; i++)
{
_exprBuilder.AppendLine().Append(_indent);
Modify(e.Bindings[i]);
if (i + 1 < e.Bindings.Count)
_exprBuilder.Append(',');
}
PopIndent();
_exprBuilder.AppendLine().Append(_indent).Append('}');
}
return false;
}
case ExpressionType.NewArrayInit:
{
var e = (NewArrayExpression)expr;
_exprBuilder.AppendFormat("new {0}[]", GetTypeName(e.Type.GetElementType()!));
if (e.Expressions.Count == 1)
{
_exprBuilder.Append(" { ");
Build(e.Expressions[0]);
_exprBuilder.Append(" }");
}
else
{
_exprBuilder.AppendLine().Append(_indent).Append('{');
PushIndent();
for (var i = 0; i < e.Expressions.Count; i++)
{
_exprBuilder.AppendLine().Append(_indent);
Build(e.Expressions[i]);
if (i + 1 < e.Expressions.Count)
_exprBuilder.Append(',');
}
PopIndent();
_exprBuilder.AppendLine().Append(_indent).Append('}');
}
return false;
}
case ExpressionType.TypeIs:
{
var e = (TypeBinaryExpression)expr;
_exprBuilder.Append('(');
Build(e.Expression);
_exprBuilder.AppendFormat(" is {0})", e.TypeOperand);
return false;
}
case ExpressionType.ListInit:
{
var e = (ListInitExpression)expr;
Build(e.NewExpression);
if (e.Initializers.Count == 1)
{
_exprBuilder.Append(" { ");
Build(e.Initializers[0].Arguments[0]);
_exprBuilder.Append(" }");
}
else
{
_exprBuilder.AppendLine().Append(_indent).Append('{');
PushIndent();
for (var i = 0; i < e.Initializers.Count; i++)
{
_exprBuilder.AppendLine().Append(_indent);
Build(e.Initializers[i].Arguments[0]);
if (i + 1 < e.Initializers.Count)
_exprBuilder.Append(',');
}
PopIndent();
_exprBuilder.AppendLine().Append(_indent).Append('}');
}
return false;
}
case ExpressionType.Invoke:
{
var e = (InvocationExpression)expr;
_exprBuilder.Append("Expression.Invoke(");
Build(e.Expression);
_exprBuilder.Append(", (");
for (var i = 0; i < e.Arguments.Count; i++)
{
Build(e.Arguments[i]);
if (i + 1 < e.Arguments.Count)
_exprBuilder.Append(", ");
}
_exprBuilder.Append("))");
return false;
}
default:
_exprBuilder.AppendLine("// Unknown expression.").Append(_indent).Append(expr);
return false;
}
}
readonly Dictionary<Type,string?> _typeNames = new ()
{
{ typeof(object), "object" },
{ typeof(bool), "bool" },
{ typeof(int), "int" },
{ typeof(string), "string" },
};
readonly StringBuilder _typeBuilder = new ();
void BuildType(Type type, MappingSchema mappingSchema)
{
if (!IsUserType(type) ||
IsAnonymous(type) ||
type.Assembly == GetType().Assembly ||
type.IsGenericType && type.GetGenericTypeDefinition() != type)
return;
var isUserName = IsUserType(type);
var name = MangleName(isUserName, type.Name, "T");
var idx = name.LastIndexOf("`");
if (idx > 0)
name = name.Substring(0, idx);
if (type.IsGenericType)
type = type.GetGenericTypeDefinition();
if (type.IsEnum)
{
// var ed = mappingSchema.GetEntityDescriptor(type); -> todo entity descriptor should contain enum mappings, otherwise fluent mappings will not be included
_typeBuilder.AppendLine("\tenum " + MangleName(isUserName, type.Name, "T") + " {");
foreach (var nm in Enum.GetNames(type))
{
var attr = "";
var valueAttribute = type.GetField(nm)!.GetCustomAttribute<MapValueAttribute>();
if (valueAttribute != null)
{
attr = "[MapValue(\"" + valueAttribute.Value + "\")] ";
}
_typeBuilder.AppendLine("\t\t" + attr + nm + " = " + Convert.ToInt64(Enum.Parse(type, nm)) + ",");
}
_typeBuilder.Remove(_typeBuilder.Length - 1, 1);
_typeBuilder.AppendLine("\t}");
return;
}
var baseClasses = CollectBaseTypes(type);
var ctors = type.GetConstructors().Select(c =>
{
var attrs = c.GetCustomAttributesData();
var attr = string.Concat(attrs.Select(a => "\r\n\t\t" + a.ToString()));
var ps = c.GetParameters().Select(p => GetTypeName(p.ParameterType) + " " + MangleName(p.Name, "p"));
return string.Format(@"{0}
public {1}({2})
{{
// throw new NotImplementedException();
}}",
attr,
name,
string.Join(", ", ps));
}).ToList();
if (ctors.Count == 1 && ctors[0].IndexOf("()") >= 0)
ctors.Clear();
var members = type.GetFields().Intersect(_usedMembers.OfType<FieldInfo>()).Select(f =>
{
var attr = "";
var ed = mappingSchema.GetEntityDescriptor(type);
if (ed != null)
{
var colum = ed.Columns.FirstOrDefault(x => x.MemberInfo == f);
if (colum != null)
{
attr += "\t\t[Column(" + (string.IsNullOrEmpty(colum.ColumnName) ? "" : "\"" + colum.ColumnName + "\"") + ")]" + Environment.NewLine;
}
else
{
attr += "\t\t[NotColumn]" + Environment.NewLine;
}
if (colum != null && colum.IsPrimaryKey)
{
attr += "\t\t[PrimaryKey]" + Environment.NewLine;
}
}
return string.Format(@"
{0} public {1} {2};",
attr,
GetTypeName(f.FieldType),
MangleName(isUserName, f.Name, "P"));
})
.Concat(
type.GetPropertiesEx().Intersect(_usedMembers.OfType<PropertyInfo>()).Select(p =>
{
var attr = "";
var ed = mappingSchema.GetEntityDescriptor(type);
if (ed != null)
{
var colum = ed.Columns.FirstOrDefault(x => x.MemberInfo == p);
if (colum != null)
{
attr += "\t\t[Column(" + (string.IsNullOrEmpty(colum.ColumnName) ? "" : "\"" + colum.ColumnName + "\"") + ")]" + Environment.NewLine;
}
else
{
attr += "\t\t[NotColumn]" + Environment.NewLine;
}
if (colum != null && colum.IsPrimaryKey)
{
attr += "\t\t[PrimaryKey]" + Environment.NewLine;
}
}
return string.Format(@"
{0} {3}{1} {2} {{ get; set; }}",
attr,
GetTypeName(p.PropertyType),
MangleName(isUserName, p.Name, "P"),
type.IsInterface ? "" : "public ");
}))
.Concat(
type.GetMethods().Intersect(_usedMembers.OfType<MethodInfo>()).Select(m =>
{
var attrs = m.GetCustomAttributesData();
var ps = m.GetParameters().Select(p => GetTypeName(p.ParameterType) + " " + MangleName(p.Name, "p"));
return string.Format(@"{0}
{5}{4}{1} {2}({3})
{{
throw new NotImplementedException();
}}",
string.Concat(attrs.Select(a => "\r\n\t\t" + a.ToString())),
GetTypeName(m.ReturnType),
MangleName(isUserName, m.Name, "M"),
string.Join(", ", ps),
m.IsStatic ? "static " :
m.IsVirtual ? "virtual " :
m.IsAbstract ? "abstract " :
"",
type.IsInterface ? "" : "public ");
}))
.ToArray();
{
var attr = "";
var ed = mappingSchema.GetEntityDescriptor(type);
if (ed != null && !type.IsInterface)
{
attr += "\t[Table(" + (string.IsNullOrEmpty(ed.TableName) ? "" : "\"" + ed.TableName + "\"") + ")]" + Environment.NewLine;
}
_typeBuilder.AppendFormat(
type.IsGenericType ?
@"
{8} {6}{7}{1} {2}<{3}>{5}
{{{4}{9}
}}
"
:
@"
{8} {6}{7}{1} {2}{5}
{{{4}{9}
}}
",
MangleName(isUserName, type.Namespace, "T"),
type.IsInterface ? "interface" : type.IsClass ? "class" : "struct",
name,
type.IsGenericType ? GetTypeNames(type.GetGenericArguments(), ",") : null,
string.Join("\r\n", ctors),
baseClasses.Length == 0 ? "" : " : " + GetTypeNames(baseClasses),
type.IsPublic ? "public " : "",
type.IsAbstract && !type.IsInterface ? "abstract " : "",
attr,
members.Length > 0 ? (ctors.Count != 0 ? "\r\n" : "") + string.Join("\r\n", members) : string.Empty);
}
}
private static Type[] CollectBaseTypes(Type type)
{
var types = new List<Type>();
var duplicateInterfaces = new HashSet<Type>();
if (type.BaseType != null && type.BaseType != typeof(object))
{
types.Add(type.BaseType);
populateBaseInterfaces(type.BaseType, duplicateInterfaces);
}
foreach (var iface in type.GetInterfaces())
if (duplicateInterfaces.Add(iface))
{
types.Add(iface);
populateBaseInterfaces(iface, duplicateInterfaces);
}
return types.ToArray();
static void populateBaseInterfaces(Type type, HashSet<Type> duplicateInterfaces)
{
foreach (var iface in type.GetInterfaces())
duplicateInterfaces.Add(iface);
}
}
string GetTypeNames(IEnumerable<Type> types, string separator = ", ")
{
return string.Join(separator, types.Select(GetTypeName));
}
bool IsAnonymous(Type type)
{
return type.Name.StartsWith("<>");
}
readonly Dictionary<string,string> _nameDic = new ();
string MangleName(Type type, string? name, string prefix)
{
return IsUserType(type) ? MangleName(name, prefix) : name ?? prefix;
}
string MangleName(bool isUserType, string? name, string prefix)
{
return isUserType ? MangleName(name, prefix) : name ?? prefix;
}
string MangleName(string? name, string prefix)
{
name ??= "";
if (!_mangleNames)
return name;
var oldNames = name.Split('.');
var newNames = new string[oldNames.Length];
for (var i = 0; i < oldNames.Length; i++)
{
if (_nameDic.TryGetValue(prefix + oldNames[i], out var mangledName))
newNames[i] = mangledName;
else
newNames[i] = _nameDic[prefix + oldNames[i]] = prefix + _nameDic.Count;
}
return string.Join(".", newNames);
}
public static List<string> SystemNamespaces = new ()
{
"System", "LinqToDB", "Microsoft"
};
bool IsUserType(Type type)
{
return IsUserNamespace(type.Namespace);
}
bool IsUserNamespace(string? @namespace)
{
return @namespace == null || SystemNamespaces.All(ns => @namespace != ns && !@namespace.StartsWith(ns + '.'));
}
string? GetTypeName(Type type)
{
if (type == null || type == typeof(object))
return null;
if (type.IsGenericParameter)
return type.ToString();
if (_typeNames.TryGetValue(type, out var name))
return name;
if (IsAnonymous(type))
{
_typeNames[type] = null;
return null;
}
if (type.IsGenericType)
{
var args = type.GetGenericArguments();
name = "";
if (type.Namespace != "System")
name = type.Namespace + ".";
name += type.Name;
var idx = name.LastIndexOf("`");
if (idx > 0)
name = name.Substring(0, idx);
if (type.GetGenericTypeDefinition() == typeof(Nullable<>))
{
name = $"{GetTypeName(args[0])}?";
}
else
{
name = string.Format("{0}<{1}>",
name,
string.Join(", ", args.Select(GetTypeName)));
}
_typeNames[type] = name;
return name;
}
if (type.Namespace == "System")
return type.Name;
return MangleName(type, type.ToString(), "T");
}
readonly HashSet<object> _usedMembers = new ();
void VisitMembers(Expression expr)
{
switch (expr.NodeType)
{
case ExpressionType.Call :
{
var ex = (MethodCallExpression)expr;
_usedMembers.Add(ex.Method);
if (ex.Method.IsGenericMethod)
{
var gmd = ex.Method.GetGenericMethodDefinition();
if (gmd != ex.Method)
_usedMembers.Add(gmd);
var ga = ex.Method.GetGenericArguments();
foreach (var type in ga)
_usedMembers.Add(type);
}
break;
}
case ExpressionType.MemberAccess :
{
var ex = (MemberExpression)expr;
_usedMembers.Add(ex.Member);
break;
}
case ExpressionType.MemberInit :
{
var ex = (MemberInitExpression)expr;
void Visit(IEnumerable<MemberBinding> bs)
{
foreach (var b in bs)
{
_usedMembers.Add(b.Member);
switch (b.BindingType)
{
case MemberBindingType.MemberBinding:
Visit(((MemberMemberBinding) b).Bindings);
break;
}
}
}
Visit(ex.Bindings);
break;
}
}
}
void VisitForDataContext(Expression expr)
{
switch (expr)
{
case ConstantExpression cont:
{
if (_dataContext == null)
{
if (cont.Value is IDataContext ctx)
_dataContext = ctx;
else if (cont.Value is IExpressionQuery expressionQuery)
_dataContext = expressionQuery.DataContext;
}
break;
}
}
}
readonly HashSet<Type> _usedTypes = new ();
void AddType(Type? type)
{
if (type == null || type == typeof(object) || type.IsGenericParameter || _usedTypes.Contains(type))
return;
_usedTypes.Add(type);
if (type.IsGenericType)
foreach (var arg in type.GetGenericArguments())
AddType(arg);
if (type.IsGenericType && type.GetGenericTypeDefinition() != type)
AddType(type.GetGenericTypeDefinition());
AddType(type.BaseType);
foreach (var i in type.GetInterfaces())
AddType(i);
}
private VisitActionVisitor<ExpressionTestGenerator>? _typesVisitor;
private VisitActionVisitor<ExpressionTestGenerator>? _membersVisitor;
private VisitActionVisitor<ExpressionTestGenerator>? _dataContextVisitor;
void VisitTypes(Expression expr)
{
AddType(expr.Type);
switch (expr.NodeType)
{
case ExpressionType.Call :
{
var ex = (MethodCallExpression)expr;
var mi = ex.Method;
AddType(mi.DeclaringType);
AddType(mi.ReturnType);
foreach (var arg in mi.GetGenericArguments())
AddType(arg);
break;
}
}
}
public string? GenerateSource(Expression expr)
{
string? fileName = null;
StreamWriter? sw = null;
try
{
var dir = Path.Combine(Path.GetTempPath(), "linq2db\\");
if (!Directory.Exists(dir))
Directory.CreateDirectory(dir);
var number = 0;//DateTime.Now.Ticks;
fileName = Path.Combine(dir, "ExpressionTest." + number + ".cs");
sw = File.CreateText(fileName);
var source = GenerateSourceString(expr);
sw.WriteLine(source);
}
catch (Exception ex)
{
if (sw != null)
{
sw.WriteLine();
sw.WriteLine(ex.GetType());
sw.WriteLine(ex.Message);
sw.WriteLine(ex.StackTrace);
}
}
finally
{
sw?.Dispose();
}
return fileName;
}
public string GenerateSourceString(Expression expr)
{
(_dataContextVisitor ??= VisitActionVisitor<ExpressionTestGenerator>.Create(this, static (ctx, e) => ctx.VisitForDataContext(e))).Visit(expr);
(_membersVisitor ??= VisitActionVisitor<ExpressionTestGenerator>.Create(this, static (ctx, e) => ctx.VisitMembers(e))).Visit(expr);
(_typesVisitor ??= VisitActionVisitor<ExpressionTestGenerator>.Create(this, static (ctx, e) => ctx.VisitTypes(e))).Visit(expr);
foreach (var typeNamespaceList in _usedTypes.OrderBy(t => t.Namespace).GroupBy(x => x.Namespace))
{
if (typeNamespaceList.All(type =>
{
return (!IsUserType(type) ||
IsAnonymous(type) ||
type.Assembly == GetType().Assembly ||
type.IsGenericType && type.GetGenericTypeDefinition() != type);
}))
continue;
_typeBuilder.AppendLine("namespace " + MangleName(IsUserNamespace(typeNamespaceList.Key), typeNamespaceList.Key, "T"));
_typeBuilder.AppendLine("{");
foreach (var type in typeNamespaceList.OrderBy(t => t.Name))
{
BuildType(type, _dataContext!.MappingSchema);
}
_typeBuilder.AppendLine("}");
}
Build(expr);
_exprBuilder.Replace("<>h__TransparentIdentifier", "tp");
_exprBuilder.Insert(0, "var query = ");
var result = string.Format(
@"//---------------------------------------------------------------------------------------------------
// This code was generated by LinqToDB.
//---------------------------------------------------------------------------------------------------
using System;
using System.Linq;
using System.Linq.Expressions;
using LinqToDB;
using NUnit.Framework;
{0}
namespace Tests.UserTests
{{
[TestFixture]
public class UserTest : TestBase
{{
[Test]
public void Test([DataSources(ProviderName.SQLite)] string context)
{{
// {1}
using (var db = GetDataContext(context))
{{
{2};
}}
}}
}}
}}
",
_typeBuilder,
_nameDic.Aggregate(expr.ToString(), (current,item) => current.Replace(item.Key.Substring(1), item.Value)),
_exprBuilder);
return result;
}
}
}
| 26.650614
| 160
| 0.570988
|
[
"MIT"
] |
AndreyAndryushinPSB/linq2db
|
Source/LinqToDB/Linq/Builder/ExpressionTestGenerator.cs
| 27,167
|
C#
|
#region Apache License Version 2.0
/*----------------------------------------------------------------
Copyright 2017 Yang Chen (cy2000@gmail.com)
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.
Detail: https://github.com/etechi/ServiceFramework/blob/master/license.md
----------------------------------------------------------------*/
#endregion Apache License Version 2.0
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace SF.Sys.Events
{
public static class TaskEventService
{
public static Task AddEventHandler<TPayload>(
this IEventSubscribeService EventSubscribeService,
Func<IEvent<TPayload>, Task> EventCallback,
EventDeliveryPolicy Policy= EventDeliveryPolicy.NoGuarantee,
CancellationToken token = default(CancellationToken)
)
{
var topic = TypeTopic<TPayload>.Name;
return AddEventHandler<TPayload>(EventSubscribeService, topic, EventCallback, Policy ,token);
}
public static async Task AddEventHandler<TPayload>(
this IEventSubscribeService EventSubscribeService,
string EventTopicFilter,
Func<IEvent<TPayload>, Task> EventCallback,
EventDeliveryPolicy Policy = EventDeliveryPolicy.NoGuarantee,
CancellationToken token= default(CancellationToken)
)
{
var tcs = new TaskCompletionSource<int>();
using (token.Register(() => tcs.TrySetResult(0)))
using (EventSubscribeService
.Subscribe<TPayload>(
EventTopicFilter,
e =>
{
if (token.IsCancellationRequested)
return Task.CompletedTask;
return EventCallback(e);
},
Policy
))
{
await tcs.Task;
}
}
}
}
| 31.971014
| 96
| 0.69583
|
[
"Apache-2.0"
] |
etechi/ServiceFramework
|
Projects/Server/Sys/SF.Sys.Events/EventServiceWithScope.cs
| 2,208
|
C#
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using Microsoft.AspNetCore.Http;
using NSubstitute;
namespace Microsoft.Identity.Web.Test.Common.Mocks
{
public static class MockHttpContextAccessor
{
public static IHttpContextAccessor CreateMockHttpContextAccessor()
{
var mockHttpContextAccessor = Substitute.For<IHttpContextAccessor>();
mockHttpContextAccessor.HttpContext = new DefaultHttpContext();
mockHttpContextAccessor.HttpContext.Request.Scheme = "https";
mockHttpContextAccessor.HttpContext.Request.Host = new HostString("IdentityDotNetSDKAutomation");
mockHttpContextAccessor.HttpContext.Request.PathBase = "/";
return mockHttpContextAccessor;
}
}
}
| 35.652174
| 109
| 0.720732
|
[
"MIT"
] |
AzureAD/microsoft-identity-web
|
tests/Microsoft.Identity.Web.Test.Common/Mocks/MockHttpContextAccessor.cs
| 822
|
C#
|
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace SimpleDnsCrypt.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.10.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("True")]
public bool IsQueryLogTabVisible {
get {
return ((bool)(this["IsQueryLogTabVisible"]));
}
set {
this["IsQueryLogTabVisible"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("False")]
public bool IsDomainBlacklistTabVisible {
get {
return ((bool)(this["IsDomainBlacklistTabVisible"]));
}
set {
this["IsDomainBlacklistTabVisible"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("False")]
public bool IsDomainBlockLogTabVisible {
get {
return ((bool)(this["IsDomainBlockLogTabVisible"]));
}
set {
this["IsDomainBlockLogTabVisible"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("False")]
public bool IsAddressBlockLogTabVisible {
get {
return ((bool)(this["IsAddressBlockLogTabVisible"]));
}
set {
this["IsAddressBlockLogTabVisible"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("False")]
public bool IsAddressBlacklistTabVisible {
get {
return ((bool)(this["IsAddressBlacklistTabVisible"]));
}
set {
this["IsAddressBlacklistTabVisible"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("True")]
public bool IsAdvancedSettingsTabVisible {
get {
return ((bool)(this["IsAdvancedSettingsTabVisible"]));
}
set {
this["IsAdvancedSettingsTabVisible"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("")]
public string PreferredLanguage {
get {
return ((string)(this["PreferredLanguage"]));
}
set {
this["PreferredLanguage"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("")]
public string DomainWhitelistRules {
get {
return ((string)(this["DomainWhitelistRules"]));
}
set {
this["DomainWhitelistRules"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("")]
public string DomainBlacklistRules {
get {
return ((string)(this["DomainBlacklistRules"]));
}
set {
this["DomainBlacklistRules"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("")]
public string DomainBlacklistFile {
get {
return ((string)(this["DomainBlacklistFile"]));
}
set {
this["DomainBlacklistFile"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("")]
public string QueryLogFile {
get {
return ((string)(this["QueryLogFile"]));
}
set {
this["QueryLogFile"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("True")]
public bool UpgradeRequired {
get {
return ((bool)(this["UpgradeRequired"]));
}
set {
this["UpgradeRequired"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("False")]
public bool StartInTray {
get {
return ((bool)(this["StartInTray"]));
}
set {
this["StartInTray"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("True")]
public bool TrayMode {
get {
return ((bool)(this["TrayMode"]));
}
set {
this["TrayMode"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("True")]
public bool InstallRedistributablePackage {
get {
return ((bool)(this["InstallRedistributablePackage"]));
}
set {
this["InstallRedistributablePackage"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("True")]
public bool BackupAndRestoreConfigOnUpdate {
get {
return ((bool)(this["BackupAndRestoreConfigOnUpdate"]));
}
set {
this["BackupAndRestoreConfigOnUpdate"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("")]
public string CloakingRulesFile {
get {
return ((string)(this["CloakingRulesFile"]));
}
set {
this["CloakingRulesFile"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("False")]
public bool IsCloakAndForwardTabVisible {
get {
return ((bool)(this["IsCloakAndForwardTabVisible"]));
}
set {
this["IsCloakAndForwardTabVisible"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("")]
public string ForwardingRulesFile {
get {
return ((string)(this["ForwardingRulesFile"]));
}
set {
this["ForwardingRulesFile"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("825")]
public int WindowWidth {
get {
return ((int)(this["WindowWidth"]));
}
set {
this["WindowWidth"] = value;
}
}
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("875")]
public int WindowHeight {
get {
return ((int)(this["WindowHeight"]));
}
set {
this["WindowHeight"] = value;
}
}
}
}
| 38.114695
| 152
| 0.569024
|
[
"MIT"
] |
instantsc/SimpleDnsCrypt
|
SimpleDnsCrypt/Properties/Settings.Designer.cs
| 10,636
|
C#
|
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
namespace AdventureWorks.Core.Domain.Entities
{
[Table("CountryRegion", Schema = "Person")]
public partial class CountryRegion
{
#region Members
[Key]
[Required]
public string CountryRegionCode { get; set; }
public DateTime ModifiedDate { get; set; }
public string Name { get; set; }
#endregion Members
#region Equals/GetHashCode
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
if (ReferenceEquals(this, obj))
{
return true;
}
CountryRegion other = obj as CountryRegion;
if (other == null) return false;
if (CountryRegionCode != other.CountryRegionCode)
return false;
if (ModifiedDate != other.ModifiedDate)
return false;
if (Name != other.Name)
return false;
return true;
}
public override int GetHashCode()
{
unchecked
{
int hash = 17;
hash = hash * 23 + (CountryRegionCode == null ? 0 : CountryRegionCode.GetHashCode());
hash = hash * 23 + (ModifiedDate == default(DateTime) ? 0 : ModifiedDate.GetHashCode());
hash = hash * 23 + (Name == null ? 0 : Name.GetHashCode());
return hash;
}
}
public static bool operator ==(CountryRegion left, CountryRegion right)
{
return Equals(left, right);
}
public static bool operator !=(CountryRegion left, CountryRegion right)
{
return !Equals(left, right);
}
#endregion Equals/GetHashCode
}
}
| 32.178082
| 104
| 0.515964
|
[
"MIT"
] |
Drizin/Harbin
|
src/AdventureWorks.Core.Domain/Entities/CountryRegion.generated.cs
| 2,351
|
C#
|
using System.ComponentModel;
namespace OfxNet
{
public enum OfxAccountType
{
NotSet,
[Description("Checking")]
CHECKING,
[Description("Savings")]
SAVINGS,
[Description("Money Market")]
MONEYMRKT,
[Description("Line of credit")]
CREDITLINE,
[Description("Certificate of Deposit")]
CD
}
}
| 18.571429
| 47
| 0.561538
|
[
"MIT"
] |
AArnott/BankingTools
|
OfxNet/Models/OfxAccountType.cs
| 392
|
C#
|
namespace WhazzupInTryavna.Data.Migrations
{
using System;
using Microsoft.EntityFrameworkCore.Migrations;
public partial class CreateActivitiesModels : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Categories",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Name = table.Column<string>(type: "nvarchar(20)", maxLength: 20, nullable: false),
Image = table.Column<string>(type: "nvarchar(max)", nullable: false),
CreatedOn = table.Column<DateTime>(type: "datetime2", nullable: false),
ModifiedOn = table.Column<DateTime>(type: "datetime2", nullable: true),
IsDeleted = table.Column<bool>(type: "bit", nullable: false),
DeletedOn = table.Column<DateTime>(type: "datetime2", nullable: true),
},
constraints: table =>
{
table.PrimaryKey("PK_Categories", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Activities",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Name = table.Column<string>(type: "nvarchar(20)", maxLength: 20, nullable: false),
CategoryId = table.Column<int>(type: "int", nullable: false),
Description = table.Column<string>(type: "nvarchar(max)", nullable: true),
Location = table.Column<string>(type: "nvarchar(100)", maxLength: 100, nullable: false),
StartTime = table.Column<DateTime>(type: "datetime2", nullable: false),
AddedByUserId = table.Column<string>(type: "nvarchar(450)", nullable: true),
CreatedOn = table.Column<DateTime>(type: "datetime2", nullable: false),
ModifiedOn = table.Column<DateTime>(type: "datetime2", nullable: true),
IsDeleted = table.Column<bool>(type: "bit", nullable: false),
DeletedOn = table.Column<DateTime>(type: "datetime2", nullable: true),
},
constraints: table =>
{
table.PrimaryKey("PK_Activities", x => x.Id);
table.ForeignKey(
name: "FK_Activities_AspNetUsers_AddedByUserId",
column: x => x.AddedByUserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_Activities_Categories_CategoryId",
column: x => x.CategoryId,
principalTable: "Categories",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "UserActivities",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
UserId = table.Column<string>(type: "nvarchar(450)", nullable: true),
ActivityId = table.Column<int>(type: "int", nullable: false),
CreatedOn = table.Column<DateTime>(type: "datetime2", nullable: false),
ModifiedOn = table.Column<DateTime>(type: "datetime2", nullable: true),
IsDeleted = table.Column<bool>(type: "bit", nullable: false),
DeletedOn = table.Column<DateTime>(type: "datetime2", nullable: true),
},
constraints: table =>
{
table.PrimaryKey("PK_UserActivities", x => x.Id);
table.ForeignKey(
name: "FK_UserActivities_Activities_ActivityId",
column: x => x.ActivityId,
principalTable: "Activities",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_UserActivities_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "Votes",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
ActivityId = table.Column<int>(type: "int", nullable: false),
UserId = table.Column<string>(type: "nvarchar(450)", nullable: true),
Value = table.Column<byte>(type: "tinyint", nullable: false),
CreatedOn = table.Column<DateTime>(type: "datetime2", nullable: false),
ModifiedOn = table.Column<DateTime>(type: "datetime2", nullable: true),
IsDeleted = table.Column<bool>(type: "bit", nullable: false),
DeletedOn = table.Column<DateTime>(type: "datetime2", nullable: true),
},
constraints: table =>
{
table.PrimaryKey("PK_Votes", x => x.Id);
table.ForeignKey(
name: "FK_Votes_Activities_ActivityId",
column: x => x.ActivityId,
principalTable: "Activities",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_Votes_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateIndex(
name: "IX_Activities_AddedByUserId",
table: "Activities",
column: "AddedByUserId");
migrationBuilder.CreateIndex(
name: "IX_Activities_CategoryId",
table: "Activities",
column: "CategoryId");
migrationBuilder.CreateIndex(
name: "IX_Activities_IsDeleted",
table: "Activities",
column: "IsDeleted");
migrationBuilder.CreateIndex(
name: "IX_Categories_IsDeleted",
table: "Categories",
column: "IsDeleted");
migrationBuilder.CreateIndex(
name: "IX_UserActivities_ActivityId",
table: "UserActivities",
column: "ActivityId");
migrationBuilder.CreateIndex(
name: "IX_UserActivities_IsDeleted",
table: "UserActivities",
column: "IsDeleted");
migrationBuilder.CreateIndex(
name: "IX_UserActivities_UserId",
table: "UserActivities",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_Votes_ActivityId",
table: "Votes",
column: "ActivityId");
migrationBuilder.CreateIndex(
name: "IX_Votes_IsDeleted",
table: "Votes",
column: "IsDeleted");
migrationBuilder.CreateIndex(
name: "IX_Votes_UserId",
table: "Votes",
column: "UserId");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "UserActivities");
migrationBuilder.DropTable(
name: "Votes");
migrationBuilder.DropTable(
name: "Activities");
migrationBuilder.DropTable(
name: "Categories");
}
}
}
| 45.251309
| 108
| 0.495661
|
[
"MIT"
] |
YavorTsanev/WhazzupInTryavna
|
Data/WhazzupInTryavna.Data/Migrations/20210701162328_CreateActivitiesModels.cs
| 8,645
|
C#
|
//
// Copyright (C) DataStax 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
//
// 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.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Cassandra.Responses;
using Cassandra.Serialization;
using Cassandra.Tasks;
namespace Cassandra.Connections.Control
{
/// <inheritdoc />
internal class TopologyRefresher : ITopologyRefresher
{
private const string SelectPeers = "SELECT * FROM system.peers";
private const string SelectPeersV2 = "SELECT * FROM system.peers_v2";
private const string SelectLocal = "SELECT * FROM system.local WHERE key='local'";
private static readonly IPAddress BindAllAddress = new IPAddress(new byte[4]);
private readonly Configuration _config;
private readonly Metadata _metadata;
/// <summary>
/// Once this is set to false, it will never be set to true again.
/// </summary>
private volatile bool _isPeersV2 = true;
public TopologyRefresher(Metadata metadata, Configuration config)
{
_metadata = metadata ?? throw new ArgumentNullException(nameof(metadata));
_config = config ?? throw new ArgumentNullException(nameof(config));
}
/// <inheritdoc />
public async Task<Host> RefreshNodeListAsync(
IConnectionEndPoint currentEndPoint, IConnection connection, ISerializer serializer)
{
ControlConnection.Logger.Info("Refreshing node list");
// safe guard against concurrent changes of this field
var localIsPeersV2 = _isPeersV2;
var localTask = SendSystemLocalRequestAsync(connection, serializer);
var peersTask = SendSystemPeersRequestAsync(localIsPeersV2, connection, serializer);
await Task.WhenAll(localTask, peersTask).ConfigureAwait(false);
var peersResponse = peersTask.Result;
localIsPeersV2 = peersResponse.IsPeersV2;
var rsPeers = _config.MetadataRequestHandler.GetRowSet(peersResponse.Response);
var localRow = _config.MetadataRequestHandler.GetRowSet(localTask.Result).FirstOrDefault();
if (localRow == null)
{
ControlConnection.Logger.Error("Local host metadata could not be retrieved");
throw new DriverInternalError("Local host metadata could not be retrieved");
}
_metadata.Partitioner = localRow.GetValue<string>("partitioner");
var host = GetAndUpdateLocalHost(currentEndPoint, localRow);
UpdatePeersInfo(localIsPeersV2, rsPeers, host);
ControlConnection.Logger.Info("Node list retrieved successfully");
return host;
}
private Task<Response> SendSystemLocalRequestAsync(IConnection connection, ISerializer serializer)
{
return _config.MetadataRequestHandler.SendMetadataRequestAsync(
connection, serializer, TopologyRefresher.SelectLocal, QueryProtocolOptions.Default);
}
private Task<PeersResponse> SendSystemPeersRequestAsync(bool isPeersV2, IConnection connection, ISerializer serializer)
{
var peersTask = _config.MetadataRequestHandler.SendMetadataRequestAsync(
connection,
serializer,
isPeersV2 ? TopologyRefresher.SelectPeersV2 : TopologyRefresher.SelectPeers,
QueryProtocolOptions.Default);
return GetPeersResponseAsync(isPeersV2, peersTask, connection, serializer);
}
/// <summary>
/// Handles fallback logic when peers_v2 table is missing.
/// </summary>
private async Task<PeersResponse> GetPeersResponseAsync(
bool isPeersV2, Task<Response> peersRequest, IConnection connection, ISerializer serializer)
{
if (!isPeersV2)
{
var peersResponse = await peersRequest.ConfigureAwait(false);
return new PeersResponse { IsPeersV2 = false, Response = peersResponse };
}
try
{
var peersResponse = await peersRequest.ConfigureAwait(false);
return new PeersResponse { IsPeersV2 = true, Response = peersResponse };
}
catch (InvalidQueryException)
{
ControlConnection.Logger.Verbose(
"Failed to retrieve data from system.peers_v2, falling back to system.peers for " +
"the remainder of this cluster instance's lifetime.");
_isPeersV2 = false;
peersRequest = _config.MetadataRequestHandler.SendMetadataRequestAsync(
connection, serializer, TopologyRefresher.SelectPeers, QueryProtocolOptions.Default);
return await GetPeersResponseAsync(false, peersRequest, connection, serializer).ConfigureAwait(false);
}
}
/// <summary>
/// Parses system.local response, creates the local Host and adds it to the Hosts collection.
/// </summary>
private Host GetAndUpdateLocalHost(IConnectionEndPoint endPoint, IRow row)
{
var hostIpEndPoint =
endPoint.GetHostIpEndPoint()
?? GetRpcEndPoint(false, row, _config.AddressTranslator, _config.ProtocolOptions.Port);
if (hostIpEndPoint == null)
{
throw new DriverInternalError("Could not parse the node's ip address from system tables.");
}
var host = _metadata.GetHost(hostIpEndPoint) ?? _metadata.AddHost(hostIpEndPoint, endPoint.ContactPoint);
// Update cluster name, DC and rack for the one node we are connected to
var clusterName = row.GetValue<string>("cluster_name");
if (clusterName != null)
{
_metadata.ClusterName = clusterName;
}
host.SetInfo(row);
return host;
}
/// <summary>
/// Parses response from system.peers and updates the hosts collection.
/// </summary>
private void UpdatePeersInfo(bool isPeersV2, IEnumerable<IRow> peersRs, Host currentHost)
{
var foundPeers = new HashSet<IPEndPoint>();
foreach (var row in peersRs)
{
var address = GetRpcEndPoint(isPeersV2, row, _config.AddressTranslator, _config.ProtocolOptions.Port);
if (address == null)
{
ControlConnection.Logger.Error("No address found for host, ignoring it.");
continue;
}
foundPeers.Add(address);
var host = _metadata.GetHost(address) ?? _metadata.AddHost(address);
host.SetInfo(row);
}
// Removes all those that seems to have been removed (since we lost the control connection or not valid contact point)
foreach (var address in _metadata.AllReplicas())
{
if (!address.Equals(currentHost.Address) && !foundPeers.Contains(address))
{
_metadata.RemoveHost(address);
}
}
}
/// <summary>
/// Parses address from system table query response and translates it using the provided <paramref name="translator"/>.
/// </summary>
internal IPEndPoint GetRpcEndPoint(bool isPeersV2, IRow row, IAddressTranslator translator, int defaultPort)
{
IPAddress address;
address = isPeersV2 ? GetRpcAddressFromPeersV2(row) : GetRpcAddressFromLocalPeersV1(row);
if (address == null)
{
return null;
}
if (TopologyRefresher.BindAllAddress.Equals(address) && !row.IsNull("peer"))
{
address = row.GetValue<IPAddress>("peer");
ControlConnection.Logger.Warning(
"Found host with 0.0.0.0 as rpc_address, using listen_address ({0}) to contact it instead. " +
"If this is incorrect you should avoid the use of 0.0.0.0 server side.", address.ToString());
}
var rpcPort = defaultPort;
if (isPeersV2)
{
var nullableRpcPort = GetRpcPortFromPeersV2(row);
if (nullableRpcPort == null)
{
ControlConnection.Logger.Warning(
"Found host with NULL native_port, using default port ({0}) to contact it instead. ", rpcPort);
}
else
{
rpcPort = nullableRpcPort.Value;
}
}
return translator.Translate(new IPEndPoint(address, rpcPort));
}
private IPAddress GetRpcAddressFromPeersV2(IRow row)
{
return row.GetValue<IPAddress>("native_address");
}
private IPAddress GetRpcAddressFromLocalPeersV1(IRow row)
{
return row.GetValue<IPAddress>("rpc_address");
}
private int? GetRpcPortFromPeersV2(IRow row)
{
return row.GetValue<int?>("native_port");
}
private class PeersResponse
{
public bool IsPeersV2 { get; set; }
public Response Response { get; set; }
}
}
}
| 40.171315
| 130
| 0.60597
|
[
"Apache-2.0"
] |
cdwiegand/csharp-driver
|
src/Cassandra/Connections/Control/TopologyRefresher.cs
| 10,085
|
C#
|
using Newtonsoft.Json;
namespace Essensoft.AspNetCore.Payment.UnionPay.Response
{
public class UnionPayForm_6_4_RefundResponse : UnionPayResponse
{
/// <summary>
/// 二维码数据
/// </summary>
[JsonProperty("qrCode")]
public string QrCode { get; set; }
/// <summary>
/// 签名
/// </summary>
[JsonProperty("signature")]
public string Signature { get; set; }
/// <summary>
/// 签名方法
/// </summary>
[JsonProperty("signMethod")]
public string SignMethod { get; set; }
/// <summary>
/// 应答码
/// </summary>
[JsonProperty("respCode")]
public string RespCode { get; set; }
/// <summary>
/// 应答信息
/// </summary>
[JsonProperty("respMsg")]
public string RespMsg { get; set; }
/// <summary>
/// 签名公钥证书
/// 使用RSA签名方式时必选,此域填写银联签名公钥证书。
/// </summary>
[JsonProperty("signPubKeyCert")]
public string SignPubKeyCert { get; set; }
/// <summary>
/// 版本号
/// </summary>
[JsonProperty("version")]
public string Version { get; set; }
/// <summary>
/// 编码方式
/// </summary>
[JsonProperty("encoding")]
public string Encoding { get; set; }
/// <summary>
/// 产品类型
/// </summary>
[JsonProperty("bizType")]
public string BizType { get; set; }
/// <summary>
/// 交易类型
/// </summary>
[JsonProperty("txnType")]
public string TxnType { get; set; }
/// <summary>
/// 交易子类
/// </summary>
[JsonProperty("txnSubType")]
public string TxnSubType { get; set; }
/// <summary>
/// 接入类型
/// </summary>
[JsonProperty("accessType")]
public string AccessType { get; set; }
/// <summary>
/// 请求方保留域
/// </summary>
[JsonProperty("reqReserved")]
public string ReqReserved { get; set; }
/// <summary>
/// 商户代码
/// </summary>
[JsonProperty("merId")]
public string MerId { get; set; }
/// <summary>
/// 商户订单号
/// </summary>
[JsonProperty("orderId")]
public string OrderId { get; set; }
/// <summary>
/// 保留域
/// </summary>
[JsonProperty("reserved")]
public string Reserved { get; set; }
}
}
| 23.857143
| 67
| 0.474651
|
[
"MIT"
] |
cenbiq/Payment
|
src/Essensoft.AspNetCore.Payment.UnionPay/Response/UnionPayForm_6_4_RefundResponse.cs
| 2,683
|
C#
|
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace DK.Wallhaven.App.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
}
}
| 37.296296
| 149
| 0.618669
|
[
"MIT"
] |
tldrlol/DK.Wallhaven
|
DK.Wallhaven.App/Properties/Settings.Designer.cs
| 1,009
|
C#
|
namespace XmlTools.Tests.CodeGenerator.FileTests
{
public class GAEB_XML_EnumElementCasing : CodeGeneratorTestsBase
{
public GAEB_XML_EnumElementCasing(): base(ParserTestFile.GAEB_XML_3_1_Schema,
SchemaCorrectorTestFile.GAEB_XML_EnumElementCasing,
SchemaCorrectorTestFile.GAEB_XML_EnumElementCasing_Expected) { }
}
}
| 40
| 85
| 0.775
|
[
"MIT"
] |
GeorgDangl/XmlTools
|
test/XmlTools.Tests/CodeGenerator/FileTests/GAEB_XML_EnumElementCasing.cs
| 360
|
C#
|
using EvolveDb.Connection;
using EvolveDb.Dialect;
using EvolveDb.Dialect.PostgreSQL;
using EvolveDb.Tests.Infrastructure;
using Xunit;
namespace EvolveDb.Tests.Integration.PostgregSql
{
[Collection("PostgreSql collection")]
public class DialectTest
{
private readonly PostgreSqlFixture _dbContainer;
public DialectTest(PostgreSqlFixture dbContainer)
{
_dbContainer = dbContainer;
if (TestContext.Local)
{
dbContainer.Run(fromScratch: true);
}
}
[Fact]
[Category(Test.PostgreSQL)]
public void Run_all_PostgreSQL_integration_tests_work()
{
// Arrange
var cnn = _dbContainer.CreateDbConnection();
var wcnn = new WrappedConnection(cnn).AssertDatabaseServerType(DBMS.PostgreSQL);
var db = DatabaseHelperFactory.GetDatabaseHelper(DBMS.PostgreSQL, wcnn);
string schemaName = "My metadata schema";
var schema = new PostgreSQLSchema(schemaName, wcnn);
// Assert
schema.AssertIsNotExists();
schema.AssertCreation();
schema.AssertExists();
schema.AssertIsEmpty();
db.AssertDefaultSchemaName("public")
.AssertApplicationLock(_dbContainer.CreateDbConnection())
.AssertMetadataTableCreation(schemaName, "changelog")
.AssertMetadataTableLock()
.AssertSchemaIsDroppableWhenNewSchemaFound(schemaName) // id:1
.AssertVersionedMigrationSave() // id:2
.AssertVersionedMigrationChecksumUpdate()
.AssertRepeatableMigrationSave(); // id:3
schema.AssertIsNotEmpty();
schema.Erase();
schema.AssertIsEmpty();
schema.Drop();
schema.AssertIsNotExists();
db.AssertCloseConnection();
}
}
}
| 32.266667
| 92
| 0.616219
|
[
"MIT"
] |
JayDZimmerman/Evolve
|
test/Evolve.Tests/Integration/PostgreSQL/DialectTest.cs
| 1,938
|
C#
|
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using OurUmbraco.Community.GitHub;
using Umbraco.Web.WebApi;
namespace OurUmbraco.Our.Api
{
public class GitHubController : UmbracoAuthorizedApiController
{
[System.Web.Http.HttpGet]
public List<LabelReport> GetLabelReport()
{
var gitHubService = new GitHubService();
var data = gitHubService.GetLabelReport();
return data.Where(x => x.NonCompliantLabels.Any() || x.HasRequiredLabels == false).ToList();
}
[System.Web.Http.HttpGet]
public ProjectsCategoriesReport GetGitHubCategoriesProjects()
{
var gitHubService = new GitHubService();
var labelReport = gitHubService.GetLabelReport();
var pcReport = new ProjectsCategoriesReport { Projects = new List<ProjectLabel>(), Categories = new List<CategoryLabel>() };
foreach (var report in labelReport.Where(x => x.Projects.Any()))
{
foreach (var project in report.Projects.OrderBy(x => x.Name))
{
var projectName = project.Name.Split('/').Skip(1).First().Replace("-", " ").ToLower();
projectName = Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(projectName);
var foundProject = pcReport.Projects.FirstOrDefault(x => x.ProjectName == projectName);
if (foundProject != null && foundProject.Repositories.Any(x => x == report.Repository) == false)
{
foundProject.Repositories.Add(report.Repository);
}
else
{
var proj = new ProjectLabel
{
Repositories = new List<string> { report.Repository },
ProjectName = projectName
};
pcReport.Projects.Add(proj);
}
}
}
foreach (var report in labelReport.Where(x => x.Categories.Any()))
{
foreach (var category in report.Categories.OrderBy(x => x.Name))
{
var categoryName = category.Name.Split('/').Skip(1).First().Replace("-", " ").ToLower();
categoryName = Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(categoryName);
var foundCategory = pcReport.Categories.FirstOrDefault(x => x.CategoryName == categoryName);
if (foundCategory != null && foundCategory.Repositories.Any(x => x == report.Repository) == false)
{
foundCategory.Repositories.Add(report.Repository);
}
else
{
var cat = new CategoryLabel
{
Repositories = new List<string> { report.Repository },
CategoryName = categoryName
};
pcReport.Categories.Add(cat);
}
}
}
return pcReport;
}
}
public class ProjectLabel
{
public string ProjectName { get; set; }
public List<string> Repositories { get; set; }
}
public class CategoryLabel
{
public string CategoryName { get; set; }
public List<string> Repositories { get; set; }
}
public class ProjectsCategoriesReport
{
public List<ProjectLabel> Projects { get; set; }
public List<CategoryLabel> Categories { get; set; }
}
}
| 38.326531
| 136
| 0.525559
|
[
"MIT"
] |
AaronSadlerUK/OurUmbraco
|
OurUmbraco/Our/Api/GitHubController.cs
| 3,758
|
C#
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using TMPro;
using Sirenix.OdinInspector;
namespace Town
{
public class SkillSlot : MonoBehaviour, IPointerClickHandler
{
public int slotNum;
[TabGroup("Ref", "Need")] [SerializeField] protected Image icon;
[TabGroup("Ref", "Need")] [SerializeField] protected SkillData skillData;
[TabGroup("Ref", "Auto")] [SerializeField] protected Town_SkillManager skillManager;
[TabGroup("Ref", "Auto")] [SerializeField] protected GameManager gm;
[TabGroup("Ref", "Auto")] [SerializeField] protected bool ableToUse;
[TabGroup("Ref", "Need")] [SerializeField] protected GameObject learnSkill;
[TabGroup("Ref", "Need")] [SerializeField] protected GameObject image;
[TabGroup("Ref", "Need")] [SerializeField] protected bool inactive;
public virtual void Initiate()
{
if (skillManager == null) skillManager = Town_SkillManager.Instance;
if (gm == null) gm = GameManager.Instance;
icon.sprite = skillData.sprite;
}
public SkillData GetSkillData() => skillData;
public void EmptySkillSlot()
{
icon.enabled = false;
skillData = null;
}
[Button]
void ExDebug() {
icon.sprite = skillData.sprite;
}
public virtual void ResetSkillButton()
{
if (image != null)
{
image.SetActive(true);
}
if (learnSkill != null)
{
learnSkill.SetActive(true);
}
ableToUse = false;
}
public void LearnSkill() {
if (gm == null) gm = GameManager.Instance;
gm.soundManager.PlaySFXSound("Confirm");
if (!inactive && gm.GetUnitStatus().curSkillPoint > 0)
{
Debug.Log("LearnSkill");
image.SetActive(false);
learnSkill.SetActive(false);
ableToUse = true;
gm.GetUnitStatus().curSkillPoint--;
skillManager.UpdateskillPointTxt();
if (gm.isTutorial)
{
TutorialController.Instance.UnArrow();
if (TutorialController.Instance.tutorialNumber == 9)
{
TutorialController.Instance.InfinityArrow(2, DirEight.B);
}
}
}
}
public virtual void OnPointerClick(PointerEventData eventData)
{
if (ableToUse)
{
skillManager.ClickSlot(this);
if (gm.isTutorial)
{
TutorialController.Instance.UnArrow();
}
}
}
}
}
| 29.08
| 92
| 0.541609
|
[
"MIT"
] |
GDtiger/TheDark
|
Assets/Scripts/UI/Town/SkillSlot.cs
| 2,908
|
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.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.Tags;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.AddImport
{
internal abstract partial class AbstractAddImportFeatureService<TSimpleNameSyntax>
{
private abstract partial class SymbolReference : Reference
{
public readonly SymbolResult<INamespaceOrTypeSymbol> SymbolResult;
protected abstract bool ShouldAddWithExistingImport(Document document);
public SymbolReference(
AbstractAddImportFeatureService<TSimpleNameSyntax> provider,
SymbolResult<INamespaceOrTypeSymbol> symbolResult)
: base(provider, new SearchResult(symbolResult))
{
SymbolResult = symbolResult;
}
protected abstract ImmutableArray<string> GetTags(Document document);
public override bool Equals(object obj)
{
var equals = base.Equals(obj);
if (!equals)
{
return false;
}
var name1 = SymbolResult.DesiredName;
var name2 = (obj as SymbolReference)?.SymbolResult.DesiredName;
return StringComparer.Ordinal.Equals(name1, name2);
}
public override int GetHashCode()
=> Hash.Combine(SymbolResult.DesiredName, base.GetHashCode());
private async Task<ImmutableArray<TextChange>> GetTextChangesAsync(
Document document, SyntaxNode contextNode,
bool placeSystemNamespaceFirst, bool hasExistingImport,
CancellationToken cancellationToken)
{
// Defer to the language to add the actual import/using.
if (hasExistingImport)
{
return ImmutableArray<TextChange>.Empty;
}
(var newContextNode, var newDocument) = await ReplaceNameNodeAsync(
contextNode, document, cancellationToken).ConfigureAwait(false);
var updatedDocument = await provider.AddImportAsync(
newContextNode, SymbolResult.Symbol, newDocument,
placeSystemNamespaceFirst, cancellationToken).ConfigureAwait(false);
var cleanedDocument = await CodeAction.CleanupDocumentAsync(
updatedDocument, cancellationToken).ConfigureAwait(false);
var textChanges = await cleanedDocument.GetTextChangesAsync(
document, cancellationToken).ConfigureAwait(false);
return textChanges.ToImmutableArray();
}
public sealed override async Task<AddImportFixData> TryGetFixDataAsync(
Document document, SyntaxNode node,
bool placeSystemNamespaceFirst, CancellationToken cancellationToken)
{
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var (description, hasExistingImport) = GetDescription(document, node, semanticModel, cancellationToken);
if (description == null)
{
return null;
}
if (hasExistingImport && !ShouldAddWithExistingImport(document))
{
return null;
}
var isFuzzy = !SearchResult.DesiredNameMatchesSourceName(document);
var tags = GetTags(document);
if (isFuzzy)
{
// The name is going to change. Make it clear in the description that this is
// going to happen.
description = $"{SearchResult.DesiredName} - {description}";
// if we were a fuzzy match, and we didn't have any glyph to show, then add the
// namespace-glyph to this item. This helps indicate that not only are we fixing
// the spelling of this name we are *also* adding a namespace. This helps as we
// have gotten feedback in the past that the 'using/import' addition was
// unexpected.
if (tags.IsDefaultOrEmpty)
{
tags = WellKnownTagArrays.Namespace;
}
}
var textChanges = await GetTextChangesAsync(
document, node, placeSystemNamespaceFirst, hasExistingImport, cancellationToken).ConfigureAwait(false);
return GetFixData(
document, textChanges, description,
tags, GetPriority(document));
}
protected abstract AddImportFixData GetFixData(
Document document, ImmutableArray<TextChange> textChanges,
string description, ImmutableArray<string> tags, CodeActionPriority priority);
protected abstract CodeActionPriority GetPriority(Document document);
protected virtual (string description, bool hasExistingImport) GetDescription(
Document document, SyntaxNode node,
SemanticModel semanticModel, CancellationToken cancellationToken)
{
return provider.GetDescription(
document, SymbolResult.Symbol, semanticModel, node, cancellationToken);
}
}
}
}
| 42.992647
| 123
| 0.604241
|
[
"MIT"
] |
06needhamt/roslyn
|
src/Features/Core/Portable/AddImport/References/SymbolReference.cs
| 5,849
|
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/shellapi.h in the Windows SDK for Windows 10.0.22000.0
// Original source is Copyright © Microsoft. All rights reserved.
namespace TerraFX.Interop.Windows;
public static partial class SHGFI
{
[NativeTypeName("#define SHGFI_ICON 0x000000100")]
public const int SHGFI_ICON = 0x000000100;
[NativeTypeName("#define SHGFI_DISPLAYNAME 0x000000200")]
public const int SHGFI_DISPLAYNAME = 0x000000200;
[NativeTypeName("#define SHGFI_TYPENAME 0x000000400")]
public const int SHGFI_TYPENAME = 0x000000400;
[NativeTypeName("#define SHGFI_ATTRIBUTES 0x000000800")]
public const int SHGFI_ATTRIBUTES = 0x000000800;
[NativeTypeName("#define SHGFI_ICONLOCATION 0x000001000")]
public const int SHGFI_ICONLOCATION = 0x000001000;
[NativeTypeName("#define SHGFI_EXETYPE 0x000002000")]
public const int SHGFI_EXETYPE = 0x000002000;
[NativeTypeName("#define SHGFI_SYSICONINDEX 0x000004000")]
public const int SHGFI_SYSICONINDEX = 0x000004000;
[NativeTypeName("#define SHGFI_LINKOVERLAY 0x000008000")]
public const int SHGFI_LINKOVERLAY = 0x000008000;
[NativeTypeName("#define SHGFI_SELECTED 0x000010000")]
public const int SHGFI_SELECTED = 0x000010000;
[NativeTypeName("#define SHGFI_ATTR_SPECIFIED 0x000020000")]
public const int SHGFI_ATTR_SPECIFIED = 0x000020000;
[NativeTypeName("#define SHGFI_LARGEICON 0x000000000")]
public const int SHGFI_LARGEICON = 0x000000000;
[NativeTypeName("#define SHGFI_SMALLICON 0x000000001")]
public const int SHGFI_SMALLICON = 0x000000001;
[NativeTypeName("#define SHGFI_OPENICON 0x000000002")]
public const int SHGFI_OPENICON = 0x000000002;
[NativeTypeName("#define SHGFI_SHELLICONSIZE 0x000000004")]
public const int SHGFI_SHELLICONSIZE = 0x000000004;
[NativeTypeName("#define SHGFI_PIDL 0x000000008")]
public const int SHGFI_PIDL = 0x000000008;
[NativeTypeName("#define SHGFI_USEFILEATTRIBUTES 0x000000010")]
public const int SHGFI_USEFILEATTRIBUTES = 0x000000010;
[NativeTypeName("#define SHGFI_ADDOVERLAYS 0x000000020")]
public const int SHGFI_ADDOVERLAYS = 0x000000020;
[NativeTypeName("#define SHGFI_OVERLAYINDEX 0x000000040")]
public const int SHGFI_OVERLAYINDEX = 0x000000040;
}
| 37.96875
| 145
| 0.767078
|
[
"MIT"
] |
reflectronic/terrafx.interop.windows
|
sources/Interop/Windows/Windows/um/shellapi/SHGFI.cs
| 2,432
|
C#
|
// Copyright 2009-2015 Josh Close and Contributors
// This file is a part of CsvHelper and is dual licensed under MS-PL and Apache 2.0.
// See LICENSE.txt for details or visit http://www.opensource.org/licenses/ms-pl.html for MS-PL and http://opensource.org/licenses/Apache-2.0 for Apache 2.0.
// http://csvhelper.com
#if !NET_2_0
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using CsvHelper.TypeConversion;
namespace CsvHelper.Configuration
{
///<summary>
/// Maps class properties to CSV fields.
///</summary>
public abstract class CsvClassMap
{
private readonly CsvPropertyMapCollection propertyMaps = new CsvPropertyMapCollection();
private readonly List<CsvPropertyReferenceMap> referenceMaps = new List<CsvPropertyReferenceMap>();
/// <summary>
/// Called to create the mappings.
/// </summary>
[Obsolete( "This method is deprecated and will be removed in the next major release. Specify your mappings in the constructor instead.", false )]
public virtual void CreateMap() {}
/// <summary>
/// Gets the constructor expression.
/// </summary>
public virtual NewExpression Constructor { get; protected set; }
/// <summary>
/// The class property mappings.
/// </summary>
public virtual CsvPropertyMapCollection PropertyMaps
{
get { return propertyMaps; }
}
/// <summary>
/// The class property reference mappings.
/// </summary>
public virtual List<CsvPropertyReferenceMap> ReferenceMaps
{
get { return referenceMaps; }
}
/// <summary>
/// Allow only internal creation of CsvClassMap.
/// </summary>
internal CsvClassMap() {}
/// <summary>
/// Gets the property map for the given property expression.
/// </summary>
/// <typeparam name="T">The type of the class the property belongs to.</typeparam>
/// <param name="expression">The property expression.</param>
/// <returns>The CsvPropertyMap for the given expression.</returns>
[Obsolete( "This method is deprecated and will be removed in the next major release.", false )]
public virtual CsvPropertyMap PropertyMap<T>( Expression<Func<T, object>> expression )
{
var property = ReflectionHelper.GetProperty( expression );
var existingMap = PropertyMaps.SingleOrDefault( m =>
m.Data.Property == property
|| m.Data.Property.Name == property.Name
&& ( m.Data.Property.DeclaringType.IsAssignableFrom( property.DeclaringType ) || property.DeclaringType.IsAssignableFrom( m.Data.Property.DeclaringType ) ) );
if( existingMap != null )
{
return existingMap;
}
var propertyMap = new CsvPropertyMap( property );
propertyMap.Data.Index = GetMaxIndex() + 1;
PropertyMaps.Add( propertyMap );
return propertyMap;
}
/// <summary>
/// Auto maps all properties for the given type. If a property
/// is mapped again it will override the existing map.
/// </summary>
/// <param name="ignoreReferences">A value indicating if references should be ignored when auto mapping.
/// True to ignore references, otherwise false.</param>
/// <param name="prefixReferenceHeaders">A value indicating if headers of reference properties should
/// get prefixed by the parent property name.
/// True to prefix, otherwise false.</param>
public virtual void AutoMap( bool ignoreReferences = false, bool prefixReferenceHeaders = false )
{
var mapParents = new LinkedList<Type>();
AutoMapInternal( this, ignoreReferences, prefixReferenceHeaders, mapParents );
}
/// <summary>
/// Get the largest index for the
/// properties and references.
/// </summary>
/// <returns>The max index.</returns>
internal int GetMaxIndex()
{
if( PropertyMaps.Count == 0 && ReferenceMaps.Count == 0 )
{
return -1;
}
var indexes = new List<int>();
if( PropertyMaps.Count > 0 )
{
indexes.Add( PropertyMaps.Max( pm => pm.Data.Index ) );
}
indexes.AddRange( ReferenceMaps.Select( referenceMap => referenceMap.GetMaxIndex() ) );
return indexes.Max();
}
/// <summary>
/// Resets the indexes based on the given start index.
/// </summary>
/// <param name="indexStart">The index start.</param>
/// <returns>The last index + 1.</returns>
internal int ReIndex( int indexStart = 0 )
{
foreach( var propertyMap in PropertyMaps )
{
if( !propertyMap.Data.IsIndexSet )
{
propertyMap.Data.Index = indexStart + propertyMap.Data.Index;
}
}
foreach( var referenceMap in ReferenceMaps )
{
indexStart = referenceMap.Data.Mapping.ReIndex( indexStart );
}
return indexStart;
}
/// <summary>
/// Auto maps the given map and checks for circular references as it goes.
/// </summary>
/// <param name="map">The map to auto map.</param>
/// <param name="ignoreReferences">A value indicating if references should be ignored when auto mapping.
/// True to ignore references, otherwise false.</param>
/// <param name="prefixReferenceHeaders">A value indicating if headers of reference properties should
/// get prefixed by the parent property name.
/// True to prefix, otherwise false.</param>
/// <param name="mapParents">The list of parents for the map.</param>
internal static void AutoMapInternal( CsvClassMap map, bool ignoreReferences, bool prefixReferenceHeaders, LinkedList<Type> mapParents, int indexStart = 0 )
{
var type = map.GetType().GetTypeInfo().BaseType.GetGenericArguments()[0];
if( typeof( IEnumerable ).IsAssignableFrom( type ) )
{
throw new CsvConfigurationException( "Types that inherit IEnumerable cannot be auto mapped. " +
"Did you accidentally call GetRecord or WriteRecord which " +
"acts on a single record instead of calling GetRecords or " +
"WriteRecords which acts on a list of records?" );
}
var properties = type.GetProperties( BindingFlags.Instance | BindingFlags.Public );
foreach( var property in properties )
{
var typeConverterType = TypeConverterFactory.GetConverter( property.PropertyType ).GetType();
if( typeConverterType == typeof( EnumerableConverter ) )
{
// The IEnumerable converter just throws an exception so skip it.
continue;
}
var isDefaultConverter = typeConverterType == typeof( DefaultTypeConverter );
var hasDefaultConstructor = property.PropertyType.GetConstructor( new Type[0] ) != null;
if( isDefaultConverter && hasDefaultConstructor )
{
if( ignoreReferences )
{
continue;
}
// If the type is not one covered by our type converters
// and it has a parameterless constructor, create a
// reference map for it.
if( CheckForCircularReference( property.PropertyType, mapParents ) )
{
continue;
}
mapParents.AddLast( type );
var refMapType = typeof( DefaultCsvClassMap<> ).MakeGenericType( property.PropertyType );
var refMap = (CsvClassMap)ReflectionHelper.CreateInstance( refMapType );
AutoMapInternal( refMap, false, prefixReferenceHeaders, mapParents, map.GetMaxIndex() + 1 );
if( refMap.PropertyMaps.Count > 0 || refMap.ReferenceMaps.Count > 0 )
{
var referenceMap = new CsvPropertyReferenceMap( property, refMap );
if( prefixReferenceHeaders )
{
referenceMap.Prefix();
}
map.ReferenceMaps.Add( referenceMap );
}
}
else
{
var propertyMap = new CsvPropertyMap( property );
propertyMap.Data.Index = map.GetMaxIndex() + 1;
if( propertyMap.Data.TypeConverter.CanConvertFrom( typeof( string ) ) ||
propertyMap.Data.TypeConverter.CanConvertTo( typeof( string ) ) && !isDefaultConverter )
{
// Only add the property map if it can be converted later on.
// If the property will use the default converter, don't add it because
// we don't want the .ToString() value to be used when auto mapping.
map.PropertyMaps.Add( propertyMap );
}
}
}
map.ReIndex( indexStart );
}
/// <summary>
/// Checks for circular references.
/// </summary>
/// <param name="type">The type to check for.</param>
/// <param name="mapParents">The list of parents to check against.</param>
/// <returns>A value indicating if a circular reference was found.
/// True if a circular reference was found, otherwise false.</returns>
internal static bool CheckForCircularReference( Type type, LinkedList<Type> mapParents )
{
if( mapParents.Count == 0 )
{
return false;
}
var node = mapParents.Last;
while( true )
{
if( node.Value == type )
{
return true;
}
node = node.Previous;
if( node == null )
{
break;
}
}
return false;
}
}
}
#endif // !NET_2_0
| 34.84556
| 163
| 0.666371
|
[
"MIT"
] |
anonymousthing/govhack2016
|
api/BrisbaneLocateAPI/BikeRacks/packages/CsvHelper.2.16.0.0/src/CsvHelper/Configuration/CsvClassMap.cs
| 9,027
|
C#
|
using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Description;
using Microsoft.Bot.Connector;
using Newtonsoft.Json;
namespace TranslatorBot
{
[BotAuthentication]
public class MessagesController : ApiController
{
/// <summary>
/// This is a simple language translator bot. Imagine you had an english twitter feed that you wanted cross post onto
/// foriegn social media sites in the language native to those sites (i.e., Vkontakte, or Futubra).
/// </summary>
public async Task<HttpResponseMessage> Post([FromBody]Activity activity)
{
if (activity.Type == ActivityTypes.Message)
{
ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));
// calculate something for us to return
int length = (activity.Text ?? string.Empty).Length;
// return the text translated into Russian
Translator t = new Translator();
Activity reply = activity.CreateReply( string.Format ( "In Russian: {0}", t.Translate( activity.Text, "en", "ru" ) ) );
await connector.Conversations.ReplyToActivityAsync(reply);
}
else
{
HandleSystemMessage(activity);
}
var response = Request.CreateResponse(HttpStatusCode.OK);
return response;
}
private Activity HandleSystemMessage(Activity message)
{
if (message.Type == ActivityTypes.DeleteUserData)
{
// Implement user deletion here
// If we handle user deletion, return a real message
}
else if (message.Type == ActivityTypes.ConversationUpdate)
{
// Handle conversation state changes, like members being added and removed
// Use Activity.MembersAdded and Activity.MembersRemoved and Activity.Action for info
// Not available in all channels
}
else if (message.Type == ActivityTypes.ContactRelationUpdate)
{
// Handle add/remove from contact lists
// Activity.From + Activity.Action represent what happened
}
else if (message.Type == ActivityTypes.Typing)
{
// Handle knowing tha the user is typing
}
else if (message.Type == ActivityTypes.Ping)
{
}
return null;
}
}
}
| 37.857143
| 135
| 0.585283
|
[
"MIT"
] |
jepickett/BotFrameworkSample
|
Translator/Controllers/MessagesController.cs
| 2,652
|
C#
|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using DocumentFormat.OpenXml.Framework;
using System;
using System.Collections.Generic;
namespace DocumentFormat.OpenXml.Packaging
{
/// <summary>
/// Defines the DocumentSettingsPart
/// </summary>
[ContentType(ContentTypeConstant)]
[RelationshipTypeAttribute(RelationshipTypeConstant)]
[PartConstraint(typeof(MailMergeRecipientDataPart), false, false)]
[PartConstraint(typeof(ImagePart), false, true)]
public partial class DocumentSettingsPart : OpenXmlPart, IFixedContentTypePart
{
internal const string ContentTypeConstant = "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml";
internal const string RelationshipTypeConstant = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/settings";
private DocumentFormat.OpenXml.Wordprocessing.Settings _rootElement;
/// <summary>
/// Creates an instance of the DocumentSettingsPart OpenXmlType
/// </summary>
internal protected DocumentSettingsPart()
{
}
/// <inheritdoc/>
public sealed override string ContentType => ContentTypeConstant;
/// <summary>
/// Gets the ImageParts of the DocumentSettingsPart
/// </summary>
public IEnumerable<ImagePart> ImageParts => GetPartsOfType<ImagePart>();
private protected override OpenXmlPartRootElement InternalRootElement
{
get
{
return _rootElement;
}
set
{
_rootElement = value as DocumentFormat.OpenXml.Wordprocessing.Settings;
}
}
/// <summary>
/// Gets the MailMergeRecipientDataPart of the DocumentSettingsPart
/// </summary>
public MailMergeRecipientDataPart MailMergeRecipientDataPart => GetSubPartOfType<MailMergeRecipientDataPart>();
internal override OpenXmlPartRootElement PartRootElement => Settings;
/// <inheritdoc/>
public sealed override string RelationshipType => RelationshipTypeConstant;
/// <summary>
/// Gets or sets the root element of this part.
/// </summary>
public DocumentFormat.OpenXml.Wordprocessing.Settings Settings
{
get
{
if (_rootElement is null)
{
LoadDomTree<DocumentFormat.OpenXml.Wordprocessing.Settings>();
}
return _rootElement;
}
set
{
if (value is null)
{
throw new ArgumentNullException(nameof(value));
}
SetDomTree(value);
}
}
/// <inheritdoc/>
internal sealed override string TargetName => "settings";
/// <inheritdoc/>
internal sealed override string TargetPath => ".";
/// <summary>
/// Adds a ImagePart to the DocumentSettingsPart
/// </summary>
/// <param name="contentType">The content type of the ImagePart</param>
/// <return>The newly added part</return>
public ImagePart AddImagePart(string contentType)
{
var childPart = new ImagePart();
InitPart(childPart, contentType);
return childPart;
}
/// <summary>
/// Adds a ImagePart to the DocumentSettingsPart
/// </summary>
/// <param name="contentType">The content type of the ImagePart</param>
/// <param name="id">The relationship id</param>
/// <return>The newly added part</return>
public ImagePart AddImagePart(string contentType, string id)
{
var childPart = new ImagePart();
InitPart(childPart, contentType, id);
return childPart;
}
/// <summary>
/// Adds a ImagePart to the DocumentSettingsPart
/// </summary>
/// <param name="partType">The part type of the ImagePart</param>
/// <param name="id">The relationship id</param>
/// <return>The newly added part</return>
public ImagePart AddImagePart(ImagePartType partType, string id)
{
var contentType = ImagePartTypeInfo.GetContentType(partType);
var partExtension = ImagePartTypeInfo.GetTargetExtension(partType);
OpenXmlPackage.PartExtensionProvider.MakeSurePartExtensionExist(contentType, partExtension);
return AddImagePart(contentType, id);
}
/// <summary>
/// Adds a ImagePart to the DocumentSettingsPart
/// </summary>
/// <param name="partType">The part type of the ImagePart</param>
/// <return>The newly added part</return>
public ImagePart AddImagePart(ImagePartType partType)
{
var contentType = ImagePartTypeInfo.GetContentType(partType);
var partExtension = ImagePartTypeInfo.GetTargetExtension(partType);
OpenXmlPackage.PartExtensionProvider.MakeSurePartExtensionExist(contentType, partExtension);
return AddImagePart(contentType);
}
/// <summary>
/// Adds a MailMergeRecipientDataPart to the DocumentSettingsPart
/// </summary>
/// <param name="contentType">The content type of the MailMergeRecipientDataPart</param>
/// <return>The newly added part</return>
public MailMergeRecipientDataPart AddMailMergeRecipientDataPart(string contentType)
{
var childPart = new MailMergeRecipientDataPart();
InitPart(childPart, contentType);
return childPart;
}
/// <summary>
/// Adds a MailMergeRecipientDataPart to the DocumentSettingsPart
/// </summary>
/// <param name="contentType">The content type of the MailMergeRecipientDataPart</param>
/// <param name="id">The relationship id</param>
/// <return>The newly added part</return>
public MailMergeRecipientDataPart AddMailMergeRecipientDataPart(string contentType, string id)
{
var childPart = new MailMergeRecipientDataPart();
InitPart(childPart, contentType, id);
return childPart;
}
/// <summary>
/// Adds a MailMergeRecipientDataPart to the DocumentSettingsPart
/// </summary>
/// <param name="partType">The part type of the MailMergeRecipientDataPart</param>
/// <param name="id">The relationship id</param>
/// <return>The newly added part</return>
public MailMergeRecipientDataPart AddMailMergeRecipientDataPart(MailMergeRecipientDataPartType partType, string id)
{
var contentType = MailMergeRecipientDataPartTypeInfo.GetContentType(partType);
var partExtension = MailMergeRecipientDataPartTypeInfo.GetTargetExtension(partType);
OpenXmlPackage.PartExtensionProvider.MakeSurePartExtensionExist(contentType, partExtension);
return AddMailMergeRecipientDataPart(contentType, id);
}
/// <summary>
/// Adds a MailMergeRecipientDataPart to the DocumentSettingsPart
/// </summary>
/// <param name="partType">The part type of the MailMergeRecipientDataPart</param>
/// <return>The newly added part</return>
public MailMergeRecipientDataPart AddMailMergeRecipientDataPart(MailMergeRecipientDataPartType partType)
{
var contentType = MailMergeRecipientDataPartTypeInfo.GetContentType(partType);
var partExtension = MailMergeRecipientDataPartTypeInfo.GetTargetExtension(partType);
OpenXmlPackage.PartExtensionProvider.MakeSurePartExtensionExist(contentType, partExtension);
return AddMailMergeRecipientDataPart(contentType);
}
/// <inheritdoc/>
internal sealed override OpenXmlPart CreatePartCore(string relationshipType)
{
ThrowIfObjectDisposed();
if (relationshipType is null)
{
throw new ArgumentNullException(nameof(relationshipType));
}
switch (relationshipType)
{
case MailMergeRecipientDataPart.RelationshipTypeConstant:
return new MailMergeRecipientDataPart();
case ImagePart.RelationshipTypeConstant:
return new ImagePart();
}
throw new ArgumentOutOfRangeException(nameof(relationshipType));
}
}
}
| 39.876147
| 136
| 0.635569
|
[
"MIT"
] |
06needhamt/Open-XML-SDK
|
src/DocumentFormat.OpenXml/GeneratedCode/Packaging/DocumentSettingsPart.g.cs
| 8,695
|
C#
|
/*
* Licensed to Jasig under one or more contributor license
* agreements. See the NOTICE file distributed with this work
* for additional information regarding copyright ownership.
* Jasig licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a
* copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#pragma warning disable 1591
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Xml;
using System.Xml.Serialization;
namespace DotNetCasClient.Validation.Schema.XmlDsig
{
[Serializable]
[DebuggerStepThrough]
[DesignerCategory("code")]
[XmlType(Namespace="http://www.w3.org/2000/09/xmldsig#")]
[XmlRoot("CanonicalizationMethod", Namespace="http://www.w3.org/2000/09/xmldsig#", IsNullable=false)]
public class CanonicalizationMethodType {
[XmlText, XmlAnyElement]
public XmlNode[] Any
{
get;
set;
}
[XmlAttribute(DataType="anyURI")]
public string Algorithm
{
get;
set;
}
}
}
#pragma warning restore 1591
| 29.807692
| 105
| 0.694839
|
[
"Apache-2.0"
] |
abisteknoloji/dotnet-cas-client
|
DotNetCasClient/Validation/Schema/XmlDsig/CanonicalizationMethodType.cs
| 1,552
|
C#
|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using Xamarin.Forms;
namespace SpartanX.MobileApp.ViewModels
{
public class ProizvodiViewModel : BaseViewModel
{
public ProizvodiViewModel()
{
komanda = new Command(async () => await Init());
}
private readonly APIService _Pservice = new APIService("Proizvodi");
private readonly APIService _VPservice = new APIService("VrsteProizvoda");
public ObservableCollection<ModelSpartanX.Proizvodi> ListaProizvoda { get; set; } = new ObservableCollection<ModelSpartanX.Proizvodi>();
public ObservableCollection<ModelSpartanX.VrstaProizvoda> ListaVrsteProizvoda { get; set; } = new ObservableCollection<ModelSpartanX.VrstaProizvoda>();
public ICommand komanda { get; set; }
public ModelSpartanX.VrstaProizvoda _sel_vrstaPro = null;
public ModelSpartanX.VrstaProizvoda vrstaPro
{
get { return _sel_vrstaPro; }
set {
SetProperty(ref _sel_vrstaPro, value);
if (value != null)
{
komanda.Execute(null);
}
}
}
public async Task Init()
{
if(ListaVrsteProizvoda.Count == 0)
{
var VPlista = await _VPservice.Get<IEnumerable<ModelSpartanX.VrstaProizvoda>>(null);
foreach (var item in VPlista)
{
ListaVrsteProizvoda.Add(item);
}
}
//var Plista = await _Pservice.Get<IEnumerable<ModelSpartanX.Proizvodi>>(null);
////prvo cistimo proizvode prije refresha
//ListaProizvoda.Clear();
//foreach (var item in Plista)
//{
// ListaProizvoda.Add(item);
//}
if (vrstaPro != null)
{
ModelSpartanX.Search.ProizvodiSearchObject search = new ModelSpartanX.Search.ProizvodiSearchObject
{
Id = vrstaPro.VrstaId
};
//if(search.Id != null)
//{
var listaById = await _Pservice.Get<List<ModelSpartanX.Proizvodi>>(search);
ListaProizvoda.Clear();
foreach (var item in listaById)
{
ListaProizvoda.Add(item);
}
//}
}
}
}
}
| 33.25
| 159
| 0.538346
|
[
"MIT"
] |
6en6ar/SpartanX_RS2_Seminarski
|
SpartanX/SpartanX.MobileApp/SpartanX.MobileApp/ViewModels/ProizvodiViewModel.cs
| 2,662
|
C#
|
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ConsoleLoggingColors.cs" company="Bosbec AB">
// Copyright © Bosbec AB 2014
// </copyright>
// <summary>
// Defines the ConsoleLoggingColors type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace Bosbec.ServiceHost.Logging.Console
{
using System;
/// <summary>
/// Defines the ConsoleLoggingColors type.
/// </summary>
public class ConsoleLoggingColors
{
/// <summary>
/// Initializes a new instance of the <see cref="ConsoleLoggingColors"/> class.
/// </summary>
public ConsoleLoggingColors()
{
Debug = ConsoleColorSetting.Foreground(ConsoleColor.Gray);
Info = ConsoleColorSetting.Foreground(ConsoleColor.Green);
Warn = ConsoleColorSetting.Foreground(ConsoleColor.Yellow);
Error = ConsoleColorSetting.Foreground(ConsoleColor.Red);
}
/// <summary>
/// Gets or sets the error.
/// </summary>
public ConsoleColorSetting Error { get; set; }
/// <summary>
/// Gets or sets the warn.
/// </summary>
public ConsoleColorSetting Warn { get; set; }
/// <summary>
/// Gets or sets the info.
/// </summary>
public ConsoleColorSetting Info { get; set; }
/// <summary>
/// Gets or sets the debug.
/// </summary>
public ConsoleColorSetting Debug { get; set; }
}
}
| 32.94
| 120
| 0.501518
|
[
"MIT"
] |
bosbec/servicehost
|
src/ServiceHost/Logging/Console/ConsoleLoggingColors.cs
| 1,650
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace peridymeAPI
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseMvc();
}
}
}
| 31.102041
| 143
| 0.662073
|
[
"MIT"
] |
yshin1209/peridymeAPI
|
Startup.cs
| 1,526
|
C#
|
using System;
using System.Linq;
using System.Text;
using O10.Core.Architecture;
using O10.Core.Cryptography;
using O10.Core.ExtensionMethods;
using O10.Core.Identity;
using O10.Core.Logging;
using O10.Crypto.ConfidentialAssets;
using O10.Crypto.Exceptions;
using O10.Crypto.Models;
using O10.Crypto.Properties;
namespace O10.Crypto.Services
{
[RegisterExtension(typeof(ISigningService), Lifetime = LifetimeManagement.Transient)]
public class StealthSigningService : ISigningService
{
protected byte[] _secretSpendKey;
protected byte[] _secretViewKey;
private readonly IIdentityKeyProvider _identityKeyProvider;
private readonly ILogger _logger;
public StealthSigningService(
IIdentityKeyProvidersRegistry identityKeyProvidersRegistry,
ILoggerService loggerService)
{
_identityKeyProvider = identityKeyProvidersRegistry.GetInstance();
PublicKeys = new IKey[2];
_logger = loggerService.GetLogger(GetType().Name);
}
public IKey[] PublicKeys { get; private set; }
public string Name => GetType().Name;
public virtual void Initialize(params byte[][] secretKeys)
{
if (secretKeys == null)
{
throw new ArgumentNullException(nameof(secretKeys));
}
if (secretKeys.Length != 2)
{
throw new WrongSecretKeysNumberException(nameof(StealthSigningService), 2);
}
_secretSpendKey = secretKeys[0];
_secretViewKey = secretKeys[1];
PublicKeys[0] = _identityKeyProvider.GetKey(CryptoHelper.GetPublicKey(_secretSpendKey));
PublicKeys[1] = _identityKeyProvider.GetKey(CryptoHelper.GetPublicKey(_secretViewKey));
}
public byte[] Sign(string msg, object? args = null)
{
byte[] message = Encoding.UTF8.GetBytes(msg);
return Sign(message, args);
}
public byte[] Sign(Memory<byte> msg, object? args = null)
{
if (!(args is StealthSignatureInput signatureInput))
{
throw new ArgumentNullException(nameof(args), $"{nameof(StealthSigningService)} expects argument args of type {nameof(StealthSignatureInput)}");
}
int index = signatureInput.KeyPosition;
byte[] otsk = CryptoHelper.GetOTSK(signatureInput.SourceTransactionKey.Value, _secretViewKey, _secretSpendKey);
byte[] keyImage = CryptoHelper.GenerateKeyImage(otsk);
byte[] msg2 = new byte[msg.Length + keyImage.Length];
Array.Copy(msg.ToArray(), 0, msg2, 0, msg.Length);
Array.Copy(keyImage, 0, msg2, msg.Length, keyImage.Length);
RingSignature[] ringSignatures = CryptoHelper.GenerateRingSignature(msg2, keyImage, signatureInput.PublicKeys, otsk, index);
byte[] signature = new byte[64 * ringSignatures.Length];
for (int i = 0; i < ringSignatures.Length; i++)
{
byte[] sig = ringSignatures[i].ToByteArray();
Array.Copy(sig, 0, signature, 64 * i, 64);
}
return signature;
}
public SignatureBase Sign<T>(PayloadBase<T> payload, object? args = null) where T: TransactionBase
{
if (payload is null)
{
throw new ArgumentNullException(nameof(payload));
}
if (!(payload.Transaction is StealthTransactionBase transaction))
{
throw new ArgumentOutOfRangeException(nameof(payload));
}
if (!(args is StealthSignatureInput signatureInput))
{
throw new ArgumentException($"{nameof(StealthSigningService)} expects argument args of type {nameof(StealthSignatureInput)}", nameof(args));
}
int index = signatureInput.KeyPosition;
byte[] otsk = CryptoHelper.GetOTSK(signatureInput.SourceTransactionKey.Value, _secretViewKey, _secretSpendKey);
byte[] keyImage = CryptoHelper.GenerateKeyImage(otsk);
transaction.KeyImage = _identityKeyProvider.GetKey(keyImage);
signatureInput.PreSigningAction?.Invoke(transaction);
RingSignature[] ringSignatures = CryptoHelper.GenerateRingSignature(payload.ToByteArray(), keyImage, signatureInput.PublicKeys, otsk, index);
return new StealthSignature
{
Sources = signatureInput.PublicKeys,
Signature = ringSignatures
};
}
public bool Verify<T>(IPayload<T> payload, SignatureBase signatureBase) where T: TransactionBase
{
if (payload is null)
{
throw new ArgumentNullException(nameof(payload));
}
if (!(payload.GetTransaction() is StealthTransactionBase transaction))
{
throw new ArgumentOutOfRangeException(nameof(payload), string.Format(Resources.ERR_WRONG_BODY_TYPE, nameof(StealthSigningService), typeof(StealthTransactionBase).FullName));
}
if (!(signatureBase is StealthSignature stealthSignature))
{
throw new ArgumentOutOfRangeException(nameof(signatureBase), string.Format(Resources.ERR_WRONG_SIGNATURE_TYPE, nameof(StealthSigningService), typeof(StealthSignature).FullName));
}
if(transaction.KeyImage == null)
{
throw new ArgumentException($"payload's {nameof(transaction.KeyImage)} is null");
}
byte[] msg = transaction.ToByteArray();
byte[] keyImage = transaction.KeyImage.ToByteArray();
return CryptoHelper.VerifyRingSignature(msg, keyImage, stealthSignature.Sources.Select(p => p.Value.ToArray()).ToArray(), stealthSignature.Signature.ToArray());
}
public bool CheckTarget(params IKey[] targetValues)
{
if (targetValues == null)
{
throw new ArgumentNullException(nameof(targetValues));
}
if (targetValues.Length != 2)
{
throw new ArgumentOutOfRangeException(nameof(targetValues));
}
try
{
_logger.LogIfDebug(() => $"{nameof(CryptoHelper)}.{nameof(CryptoHelper.IsDestinationKeyMine)}({targetValues[0]}, {targetValues[1]}, {_secretViewKey.ToHexString()}, {PublicKeys[0].Value.ToArray().ToHexString()})");
bool res = CryptoHelper.IsDestinationKeyMine(targetValues[0].ToByteArray(), targetValues[1].ToByteArray(), _secretViewKey, PublicKeys[0].Value.ToArray());
return res;
}
catch (Exception ex)
{
_logger.Error($"Failure at {nameof(CryptoHelper)}.{nameof(CryptoHelper.IsDestinationKeyMine)}", ex);
_logger.Error($"args: {nameof(CryptoHelper)}.{nameof(CryptoHelper.IsDestinationKeyMine)}({targetValues[0]}, {targetValues[1]}, {_secretViewKey.ToHexString()}, {PublicKeys[0].Value.ToArray().ToHexString()})");
throw;
}
}
}
}
| 40.105556
| 229
| 0.623078
|
[
"Apache-2.0"
] |
muaddibco/O10city
|
Common/Crypto/O10.Crypto/Services/StealthSigningService.cs
| 7,221
|
C#
|
using System;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using Common.Interfaces;
namespace Common.Cryptography
{
public static class Authenticator
{
/// <summary>
/// Login password
/// </summary>
public static string Password { get; private set; } = "admin";
/// <summary>
/// Preferred account expansion access. 0 = Vanilla, 1 = TBC etc
/// </summary>
public static byte ExpansionLevel { get; private set; } = 1;
/// <summary>
/// Build as sent by the client
/// </summary>
public static uint ClientBuild { get; set; }
/// <summary>
/// Packet coder/crypt handler
/// </summary>
public static PacketCrypt PacketCrypt { get; private set; }
/// <summary>
/// TODO fix this at some point
/// </summary>
public static readonly byte[] Reconnect_Challenge =
{
0x02, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09,
0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x01, 0x02, 0x03, 0x04,
0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10
};
#region Private Vars
private static readonly byte[] N =
{
0x89, 0x4B, 0x64, 0x5E, 0x89, 0xE1, 0x53, 0x5B,
0xBD, 0xAD, 0x5B, 0x8B, 0x29, 0x06, 0x50, 0x53,
0x08, 0x01, 0xB1, 0x8E, 0xBF, 0xBF, 0x5E, 0x8F,
0xAB, 0x3C, 0x82, 0x87, 0x2A, 0x3E, 0x9B, 0xB7
};
private static readonly byte[] Salt =
{
0xAD, 0xD0, 0x3A, 0x31, 0xD2, 0x71, 0x14, 0x46,
0x75, 0xF2, 0x70, 0x7E, 0x50, 0x26, 0xB6, 0xD2,
0xF1, 0x86, 0x59, 0x99, 0x76, 0x02, 0x50, 0xAA,
0xB9, 0x45, 0xE0, 0x9E, 0xDD, 0x2A, 0xA3, 0x45,
};
private static readonly byte[] RN = N.Reverse().ToArray();
private static BigInteger B;
private static BigInteger V;
private static byte[] RB;
private static BigInteger K;
private static BigInteger G;
private static byte[] BUsername;
#endregion Private Vars
#region Methods
public static void Clear() => PacketCrypt.Clear();
public static byte[] LogonChallenge(IPacketReader packet)
{
packet.Position = 11;
ClientBuild = packet.ReadUInt16();
packet.Position = 33; // Skip to username
BUsername = packet.ReadBytes(packet.ReadByte()); // Read username
string username = Encoding.ASCII.GetString(BUsername);
byte[] x;
using (SHA1 sha = new SHA1CryptoServiceProvider())
{
byte[] user = Encoding.ASCII.GetBytes(username.ToUpper() + ":" + Password.ToUpper());
byte[] res = Salt.Concat(sha.ComputeHash(user, 0, user.Length)).ToArray();
x = sha.ComputeHash(res, 0, res.Length).Reverse().ToArray();
}
byte[] b = new byte[20];
new Random().NextBytes(b);
RB = b.Reverse().ToArray();
G = new BigInteger(new byte[] { 7 });
V = G.ModPow(new BigInteger(x), new BigInteger(RN));
K = new BigInteger(new byte[] { 3 });
BigInteger temp = (K * V) + G.ModPow(new BigInteger(RB), new BigInteger(RN));
B = temp % new BigInteger(RN);
int size = ClientBuild < 5428 ? 118 : 119;
byte[] result = new byte[size];
Array.Copy(B.GetBytes(32).Reverse().ToArray(), 0, result, 3, 32);
result[35] = 1;
result[36] = 7;
result[37] = 32;
Array.Copy(N, 0, result, 38, N.Length);
Array.Copy(Salt, 0, result, 70, Salt.Length);
return result;
}
public static byte[] LogonProof(IPacketReader packet)
{
byte[] A = packet.ReadBytes(32);
byte[] kM1 = packet.ReadBytes(20);
byte[] rA = A.Reverse().ToArray();
byte[] AB = A.Concat(B.GetBytes(32).Reverse()).ToArray();
if (new BigInteger(A) % new BigInteger(N) == 0)
return new byte[1];
SHA1 sha1 = new SHA1CryptoServiceProvider();
byte[] rU = sha1.ComputeHash(AB).Reverse().ToArray();
// SS_Hash
BigInteger s = V.ModPow(new BigInteger(rU), new BigInteger(RN));
s *= new BigInteger(rA);
s = s.ModPow(new BigInteger(RB), new BigInteger(RN));
byte[] S1 = new byte[16];
byte[] S2 = new byte[16];
byte[] S = s.GetBytes(32);
byte[] rS = S.Reverse().ToArray();
for (int t = 0; t < 16; t++)
{
S1[t] = rS[t * 2];
S2[t] = rS[(t * 2) + 1];
}
byte[] hashS1 = sha1.ComputeHash(S1);
byte[] hashS2 = sha1.ComputeHash(S2);
byte[] ss_hash = new byte[hashS1.Length + hashS2.Length];
for (int t = 0; t < hashS1.Length; t++)
{
ss_hash[t * 2] = hashS1[t];
ss_hash[(t * 2) + 1] = hashS2[t];
}
// calc M1
byte[] M1;
byte[] NHash = sha1.ComputeHash(N);
byte[] GHash = sha1.ComputeHash(G.GetBytes());
byte[] NG_Hash = new byte[20];
for (int t = 0; t < 20; t++)
NG_Hash[t] = (byte)(NHash[t] ^ GHash[t]);
var tmp = NG_Hash.Concat(sha1.ComputeHash(BUsername))
.Concat(Salt)
.Concat(A)
.Concat(B.GetBytes(32).Reverse())
.Concat(ss_hash);
M1 = sha1.ComputeHash(tmp.ToArray());
// calc M2
byte[] M2;
tmp = A.Concat(M1).Concat(ss_hash);
M2 = sha1.ComputeHash(tmp.ToArray());
sha1.Dispose();
// instantiate coders/cryptors
PacketCrypt = new PacketCrypt(ss_hash, ClientBuild);
// additional information, always zeroed
int extradata = 0;
if (ClientBuild < 6178 || ClientBuild == 6180)
extradata = 04; // uint unk
else if (ClientBuild < 8089)
extradata = 06; // uint unk, ushort unkFlags
else
extradata = 10; // uint account flag, uint surveyId, ushort unkFlags
byte[] result = new byte[22 + extradata];
result[0] = 1;
Array.Copy(M2, 0, result, 2, M2.Length);
return result;
}
public static void LoadConfig()
{
var parser = new INIParser("settings.conf");
if (parser.TryGetValue("Settings", "Expansion", out byte exp))
ExpansionLevel = exp;
if (parser.TryGetValue("Settings", "Password", out string pass))
Password = pass;
}
#endregion
}
}
| 35.105
| 101
| 0.508617
|
[
"MIT"
] |
Ghaster/AIO-Sandbox
|
Common/Cryptography/Authenticator.cs
| 7,023
|
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.
// ----------------------------------------------------------------------------------
namespace Microsoft.WindowsAzure.Commands.ServiceManagement.Extensions
{
using Model.PersistentVMModel;
using System;
using System.Linq;
using System.Management.Automation;
using System.Security.Cryptography.X509Certificates;
using Utilities.Common;
/// <summary>
/// Set Windows Azure Service Remote Desktop Extension.
/// </summary>
[Cmdlet(VerbsCommon.Set, "AzureServiceRemoteDesktopExtension", DefaultParameterSetName = "SetExtension"), OutputType(typeof(ManagementOperationContext))]
public class SetAzureServiceRemoteDesktopExtensionCommand : BaseAzureServiceRemoteDesktopExtensionCmdlet
{
[Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ParameterSetName = "SetExtension", HelpMessage = "Cloud Service Name")]
[Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ParameterSetName = "SetExtensionUsingThumbprint", HelpMessage = "Cloud Service Name")]
public override string ServiceName
{
get;
set;
}
[Parameter(Position = 1, ValueFromPipelineByPropertyName = true, ParameterSetName = "SetExtension", HelpMessage = "Production (default) or Staging.")]
[Parameter(Position = 1, ValueFromPipelineByPropertyName = true, ParameterSetName = "SetExtensionUsingThumbprint", HelpMessage = "Production (default) or Staging.")]
[ValidateSet(DeploymentSlotType.Production, DeploymentSlotType.Staging, IgnoreCase = true)]
public override string Slot
{
get;
set;
}
[Parameter(Position = 2, ValueFromPipelineByPropertyName = true, ParameterSetName = "SetExtension", HelpMessage = "Default All Roles, or specify ones for Named Roles.")]
[Parameter(Position = 2, ValueFromPipelineByPropertyName = true, ParameterSetName = "SetExtensionUsingThumbprint", HelpMessage = "Default All Roles, or specify ones for Named Roles.")]
[ValidateNotNullOrEmpty]
public override string[] Role
{
get;
set;
}
[Parameter(Position = 3, ValueFromPipelineByPropertyName = true, ParameterSetName = "SetExtension", HelpMessage = "X509Certificate used to encrypt password.")]
[ValidateNotNullOrEmpty]
public override X509Certificate2 X509Certificate
{
get;
set;
}
[Parameter(Position = 3, ValueFromPipelineByPropertyName = true, Mandatory = true, ParameterSetName = "SetExtensionUsingThumbprint", HelpMessage = "Thumbprint of a certificate used for encryption.")]
[ValidateNotNullOrEmpty]
public override string CertificateThumbprint
{
get;
set;
}
[Parameter(Position = 4, ValueFromPipelineByPropertyName = true, ParameterSetName = "SetExtension", HelpMessage = "Algorithm associated with the Thumbprint.")]
[Parameter(Position = 4, ValueFromPipelineByPropertyName = true, ParameterSetName = "SetExtensionUsingThumbprint", HelpMessage = "Algorithm associated with the Thumbprint.")]
[ValidateNotNullOrEmpty]
public override string ThumbprintAlgorithm
{
get;
set;
}
[Parameter(Position = 5, ValueFromPipelineByPropertyName = true, Mandatory = true, ParameterSetName = "SetExtension", HelpMessage = "Remote Desktop Credential")]
[Parameter(Position = 5, ValueFromPipelineByPropertyName = true, Mandatory = true, ParameterSetName = "SetExtensionUsingThumbprint", HelpMessage = "Remote Desktop Credential ")]
[ValidateNotNullOrEmpty]
public override PSCredential Credential
{
get;
set;
}
[Parameter(Position = 6, ValueFromPipelineByPropertyName = true, ParameterSetName = "SetExtension", HelpMessage = "Remote Desktop User Expiration Date")]
[Parameter(Position = 6, ValueFromPipelineByPropertyName = true, ParameterSetName = "SetExtensionUsingThumbprint", HelpMessage = "Remote Desktop User Expiration Date")]
[ValidateNotNullOrEmpty]
public override DateTime Expiration
{
get;
set;
}
protected override void ValidateParameters()
{
base.ValidateParameters();
ValidateService();
ValidateDeployment();
ValidateRoles();
ValidateThumbprint(true);
Expiration = Expiration.Equals(default(DateTime)) ? DateTime.Now.AddMonths(12) : Expiration;
ValidateConfiguration();
}
public void ExecuteCommand()
{
ValidateParameters();
ExtensionConfigurationInput context = new ExtensionConfigurationInput
{
ProviderNameSpace = ProviderNamespace,
Type = ExtensionName,
CertificateThumbprint = CertificateThumbprint,
ThumbprintAlgorithm = ThumbprintAlgorithm,
X509Certificate = X509Certificate,
PublicConfiguration = PublicConfiguration,
PrivateConfiguration = PrivateConfiguration,
Roles = new ExtensionRoleList(Role != null && Role.Any() ? Role.Select(r => new ExtensionRole(r)) : Enumerable.Repeat(new ExtensionRole(), 1))
};
var extConfig = ExtensionManager.InstallExtension(context, Slot, Deployment.ExtensionConfiguration);
ChangeDeployment(extConfig);
}
protected override void OnProcessRecord()
{
ExecuteCommand();
}
}
}
| 48.291045
| 208
| 0.643641
|
[
"MIT"
] |
stankovski/azure-sdk-tools
|
src/ServiceManagement/Compute/Commands.ServiceManagement/Extensions/RDP/SetAzureServiceRemoteDesktopExtension.cs
| 6,340
|
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;
using Azure.ResourceManager.CosmosDB.Models;
namespace Azure.ResourceManager.CosmosDB
{
/// <summary> A class representing collection of SqlUserDefinedFunction and their operations over its parent. </summary>
public partial class SqlUserDefinedFunctionCollection : ArmCollection, IEnumerable<SqlUserDefinedFunction>, IAsyncEnumerable<SqlUserDefinedFunction>
{
private readonly ClientDiagnostics _sqlUserDefinedFunctionSqlResourcesClientDiagnostics;
private readonly SqlResourcesRestOperations _sqlUserDefinedFunctionSqlResourcesRestClient;
/// <summary> Initializes a new instance of the <see cref="SqlUserDefinedFunctionCollection"/> class for mocking. </summary>
protected SqlUserDefinedFunctionCollection()
{
}
/// <summary> Initializes a new instance of the <see cref="SqlUserDefinedFunctionCollection"/> 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 SqlUserDefinedFunctionCollection(ArmClient client, ResourceIdentifier id) : base(client, id)
{
_sqlUserDefinedFunctionSqlResourcesClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.CosmosDB", SqlUserDefinedFunction.ResourceType.Namespace, DiagnosticOptions);
TryGetApiVersion(SqlUserDefinedFunction.ResourceType, out string sqlUserDefinedFunctionSqlResourcesApiVersion);
_sqlUserDefinedFunctionSqlResourcesRestClient = new SqlResourcesRestOperations(Pipeline, DiagnosticOptions.ApplicationId, BaseUri, sqlUserDefinedFunctionSqlResourcesApiVersion);
#if DEBUG
ValidateResourceId(Id);
#endif
}
internal static void ValidateResourceId(ResourceIdentifier id)
{
if (id.ResourceType != SqlContainer.ResourceType)
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, SqlContainer.ResourceType), nameof(id));
}
/// <summary>
/// Create or update an Azure Cosmos DB SQL userDefinedFunction
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/containers/{containerName}/userDefinedFunctions/{userDefinedFunctionName}
/// Operation Id: SqlResources_CreateUpdateSqlUserDefinedFunction
/// </summary>
/// <param name="waitUntil"> "F:Azure.WaitUntil.Completed" if the method should wait to return until the long-running operation has completed on the service; "F:Azure.WaitUntil.Started" if it should return after starting the operation. For more information on long-running operations, please see <see href="https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/LongRunningOperations.md"> Azure.Core Long-Running Operation samples</see>. </param>
/// <param name="userDefinedFunctionName"> Cosmos DB userDefinedFunction name. </param>
/// <param name="createUpdateSqlUserDefinedFunctionParameters"> The parameters to provide for the current SQL userDefinedFunction. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="userDefinedFunctionName"/> is an empty string, and was expected to be non-empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="userDefinedFunctionName"/> or <paramref name="createUpdateSqlUserDefinedFunctionParameters"/> is null. </exception>
public virtual async Task<ArmOperation<SqlUserDefinedFunction>> CreateOrUpdateAsync(WaitUntil waitUntil, string userDefinedFunctionName, SqlUserDefinedFunctionCreateUpdateData createUpdateSqlUserDefinedFunctionParameters, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(userDefinedFunctionName, nameof(userDefinedFunctionName));
Argument.AssertNotNull(createUpdateSqlUserDefinedFunctionParameters, nameof(createUpdateSqlUserDefinedFunctionParameters));
using var scope = _sqlUserDefinedFunctionSqlResourcesClientDiagnostics.CreateScope("SqlUserDefinedFunctionCollection.CreateOrUpdate");
scope.Start();
try
{
var response = await _sqlUserDefinedFunctionSqlResourcesRestClient.CreateUpdateSqlUserDefinedFunctionAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Parent.Name, Id.Parent.Name, Id.Name, userDefinedFunctionName, createUpdateSqlUserDefinedFunctionParameters, cancellationToken).ConfigureAwait(false);
var operation = new CosmosDBArmOperation<SqlUserDefinedFunction>(new SqlUserDefinedFunctionOperationSource(Client), _sqlUserDefinedFunctionSqlResourcesClientDiagnostics, Pipeline, _sqlUserDefinedFunctionSqlResourcesRestClient.CreateCreateUpdateSqlUserDefinedFunctionRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Parent.Name, Id.Parent.Name, Id.Name, userDefinedFunctionName, createUpdateSqlUserDefinedFunctionParameters).Request, response, OperationFinalStateVia.Location);
if (waitUntil == WaitUntil.Completed)
await operation.WaitForCompletionAsync(cancellationToken).ConfigureAwait(false);
return operation;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Create or update an Azure Cosmos DB SQL userDefinedFunction
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/containers/{containerName}/userDefinedFunctions/{userDefinedFunctionName}
/// Operation Id: SqlResources_CreateUpdateSqlUserDefinedFunction
/// </summary>
/// <param name="waitUntil"> "F:Azure.WaitUntil.Completed" if the method should wait to return until the long-running operation has completed on the service; "F:Azure.WaitUntil.Started" if it should return after starting the operation. For more information on long-running operations, please see <see href="https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/core/Azure.Core/samples/LongRunningOperations.md"> Azure.Core Long-Running Operation samples</see>. </param>
/// <param name="userDefinedFunctionName"> Cosmos DB userDefinedFunction name. </param>
/// <param name="createUpdateSqlUserDefinedFunctionParameters"> The parameters to provide for the current SQL userDefinedFunction. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="userDefinedFunctionName"/> is an empty string, and was expected to be non-empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="userDefinedFunctionName"/> or <paramref name="createUpdateSqlUserDefinedFunctionParameters"/> is null. </exception>
public virtual ArmOperation<SqlUserDefinedFunction> CreateOrUpdate(WaitUntil waitUntil, string userDefinedFunctionName, SqlUserDefinedFunctionCreateUpdateData createUpdateSqlUserDefinedFunctionParameters, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(userDefinedFunctionName, nameof(userDefinedFunctionName));
Argument.AssertNotNull(createUpdateSqlUserDefinedFunctionParameters, nameof(createUpdateSqlUserDefinedFunctionParameters));
using var scope = _sqlUserDefinedFunctionSqlResourcesClientDiagnostics.CreateScope("SqlUserDefinedFunctionCollection.CreateOrUpdate");
scope.Start();
try
{
var response = _sqlUserDefinedFunctionSqlResourcesRestClient.CreateUpdateSqlUserDefinedFunction(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Parent.Name, Id.Parent.Name, Id.Name, userDefinedFunctionName, createUpdateSqlUserDefinedFunctionParameters, cancellationToken);
var operation = new CosmosDBArmOperation<SqlUserDefinedFunction>(new SqlUserDefinedFunctionOperationSource(Client), _sqlUserDefinedFunctionSqlResourcesClientDiagnostics, Pipeline, _sqlUserDefinedFunctionSqlResourcesRestClient.CreateCreateUpdateSqlUserDefinedFunctionRequest(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Parent.Name, Id.Parent.Name, Id.Name, userDefinedFunctionName, createUpdateSqlUserDefinedFunctionParameters).Request, response, OperationFinalStateVia.Location);
if (waitUntil == WaitUntil.Completed)
operation.WaitForCompletion(cancellationToken);
return operation;
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Gets the SQL userDefinedFunction under an existing Azure Cosmos DB database account.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/containers/{containerName}/userDefinedFunctions/{userDefinedFunctionName}
/// Operation Id: SqlResources_GetSqlUserDefinedFunction
/// </summary>
/// <param name="userDefinedFunctionName"> Cosmos DB userDefinedFunction name. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="userDefinedFunctionName"/> is an empty string, and was expected to be non-empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="userDefinedFunctionName"/> is null. </exception>
public virtual async Task<Response<SqlUserDefinedFunction>> GetAsync(string userDefinedFunctionName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(userDefinedFunctionName, nameof(userDefinedFunctionName));
using var scope = _sqlUserDefinedFunctionSqlResourcesClientDiagnostics.CreateScope("SqlUserDefinedFunctionCollection.Get");
scope.Start();
try
{
var response = await _sqlUserDefinedFunctionSqlResourcesRestClient.GetSqlUserDefinedFunctionAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Parent.Name, Id.Parent.Name, Id.Name, userDefinedFunctionName, cancellationToken).ConfigureAwait(false);
if (response.Value == null)
throw new RequestFailedException(response.GetRawResponse());
return Response.FromValue(new SqlUserDefinedFunction(Client, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Gets the SQL userDefinedFunction under an existing Azure Cosmos DB database account.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/containers/{containerName}/userDefinedFunctions/{userDefinedFunctionName}
/// Operation Id: SqlResources_GetSqlUserDefinedFunction
/// </summary>
/// <param name="userDefinedFunctionName"> Cosmos DB userDefinedFunction name. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="userDefinedFunctionName"/> is an empty string, and was expected to be non-empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="userDefinedFunctionName"/> is null. </exception>
public virtual Response<SqlUserDefinedFunction> Get(string userDefinedFunctionName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(userDefinedFunctionName, nameof(userDefinedFunctionName));
using var scope = _sqlUserDefinedFunctionSqlResourcesClientDiagnostics.CreateScope("SqlUserDefinedFunctionCollection.Get");
scope.Start();
try
{
var response = _sqlUserDefinedFunctionSqlResourcesRestClient.GetSqlUserDefinedFunction(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Parent.Name, Id.Parent.Name, Id.Name, userDefinedFunctionName, cancellationToken);
if (response.Value == null)
throw new RequestFailedException(response.GetRawResponse());
return Response.FromValue(new SqlUserDefinedFunction(Client, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
/// <summary>
/// Lists the SQL userDefinedFunction under an existing Azure Cosmos DB database account.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/containers/{containerName}/userDefinedFunctions
/// Operation Id: SqlResources_ListSqlUserDefinedFunctions
/// </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <returns> An async collection of <see cref="SqlUserDefinedFunction" /> that may take multiple service requests to iterate over. </returns>
public virtual AsyncPageable<SqlUserDefinedFunction> GetAllAsync(CancellationToken cancellationToken = default)
{
async Task<Page<SqlUserDefinedFunction>> FirstPageFunc(int? pageSizeHint)
{
using var scope = _sqlUserDefinedFunctionSqlResourcesClientDiagnostics.CreateScope("SqlUserDefinedFunctionCollection.GetAll");
scope.Start();
try
{
var response = await _sqlUserDefinedFunctionSqlResourcesRestClient.ListSqlUserDefinedFunctionsAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Parent.Name, Id.Parent.Name, Id.Name, cancellationToken: cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value.Select(value => new SqlUserDefinedFunction(Client, value)), null, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, null);
}
/// <summary>
/// Lists the SQL userDefinedFunction under an existing Azure Cosmos DB database account.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/containers/{containerName}/userDefinedFunctions
/// Operation Id: SqlResources_ListSqlUserDefinedFunctions
/// </summary>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <returns> A collection of <see cref="SqlUserDefinedFunction" /> that may take multiple service requests to iterate over. </returns>
public virtual Pageable<SqlUserDefinedFunction> GetAll(CancellationToken cancellationToken = default)
{
Page<SqlUserDefinedFunction> FirstPageFunc(int? pageSizeHint)
{
using var scope = _sqlUserDefinedFunctionSqlResourcesClientDiagnostics.CreateScope("SqlUserDefinedFunctionCollection.GetAll");
scope.Start();
try
{
var response = _sqlUserDefinedFunctionSqlResourcesRestClient.ListSqlUserDefinedFunctions(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Parent.Name, Id.Parent.Name, Id.Name, cancellationToken: cancellationToken);
return Page.FromValues(response.Value.Value.Select(value => new SqlUserDefinedFunction(Client, value)), null, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateEnumerable(FirstPageFunc, null);
}
/// <summary>
/// Checks to see if the resource exists in azure.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/containers/{containerName}/userDefinedFunctions/{userDefinedFunctionName}
/// Operation Id: SqlResources_GetSqlUserDefinedFunction
/// </summary>
/// <param name="userDefinedFunctionName"> Cosmos DB userDefinedFunction name. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="userDefinedFunctionName"/> is an empty string, and was expected to be non-empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="userDefinedFunctionName"/> is null. </exception>
public virtual async Task<Response<bool>> ExistsAsync(string userDefinedFunctionName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(userDefinedFunctionName, nameof(userDefinedFunctionName));
using var scope = _sqlUserDefinedFunctionSqlResourcesClientDiagnostics.CreateScope("SqlUserDefinedFunctionCollection.Exists");
scope.Start();
try
{
var response = await GetIfExistsAsync(userDefinedFunctionName, 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: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/containers/{containerName}/userDefinedFunctions/{userDefinedFunctionName}
/// Operation Id: SqlResources_GetSqlUserDefinedFunction
/// </summary>
/// <param name="userDefinedFunctionName"> Cosmos DB userDefinedFunction name. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="userDefinedFunctionName"/> is an empty string, and was expected to be non-empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="userDefinedFunctionName"/> is null. </exception>
public virtual Response<bool> Exists(string userDefinedFunctionName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(userDefinedFunctionName, nameof(userDefinedFunctionName));
using var scope = _sqlUserDefinedFunctionSqlResourcesClientDiagnostics.CreateScope("SqlUserDefinedFunctionCollection.Exists");
scope.Start();
try
{
var response = GetIfExists(userDefinedFunctionName, 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: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/containers/{containerName}/userDefinedFunctions/{userDefinedFunctionName}
/// Operation Id: SqlResources_GetSqlUserDefinedFunction
/// </summary>
/// <param name="userDefinedFunctionName"> Cosmos DB userDefinedFunction name. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="userDefinedFunctionName"/> is an empty string, and was expected to be non-empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="userDefinedFunctionName"/> is null. </exception>
public virtual async Task<Response<SqlUserDefinedFunction>> GetIfExistsAsync(string userDefinedFunctionName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(userDefinedFunctionName, nameof(userDefinedFunctionName));
using var scope = _sqlUserDefinedFunctionSqlResourcesClientDiagnostics.CreateScope("SqlUserDefinedFunctionCollection.GetIfExists");
scope.Start();
try
{
var response = await _sqlUserDefinedFunctionSqlResourcesRestClient.GetSqlUserDefinedFunctionAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Parent.Name, Id.Parent.Name, Id.Name, userDefinedFunctionName, cancellationToken: cancellationToken).ConfigureAwait(false);
if (response.Value == null)
return Response.FromValue<SqlUserDefinedFunction>(null, response.GetRawResponse());
return Response.FromValue(new SqlUserDefinedFunction(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: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/containers/{containerName}/userDefinedFunctions/{userDefinedFunctionName}
/// Operation Id: SqlResources_GetSqlUserDefinedFunction
/// </summary>
/// <param name="userDefinedFunctionName"> Cosmos DB userDefinedFunction name. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentException"> <paramref name="userDefinedFunctionName"/> is an empty string, and was expected to be non-empty. </exception>
/// <exception cref="ArgumentNullException"> <paramref name="userDefinedFunctionName"/> is null. </exception>
public virtual Response<SqlUserDefinedFunction> GetIfExists(string userDefinedFunctionName, CancellationToken cancellationToken = default)
{
Argument.AssertNotNullOrEmpty(userDefinedFunctionName, nameof(userDefinedFunctionName));
using var scope = _sqlUserDefinedFunctionSqlResourcesClientDiagnostics.CreateScope("SqlUserDefinedFunctionCollection.GetIfExists");
scope.Start();
try
{
var response = _sqlUserDefinedFunctionSqlResourcesRestClient.GetSqlUserDefinedFunction(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Parent.Name, Id.Parent.Name, Id.Name, userDefinedFunctionName, cancellationToken: cancellationToken);
if (response.Value == null)
return Response.FromValue<SqlUserDefinedFunction>(null, response.GetRawResponse());
return Response.FromValue(new SqlUserDefinedFunction(Client, response.Value), response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
IEnumerator<SqlUserDefinedFunction> IEnumerable<SqlUserDefinedFunction>.GetEnumerator()
{
return GetAll().GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetAll().GetEnumerator();
}
IAsyncEnumerator<SqlUserDefinedFunction> IAsyncEnumerable<SqlUserDefinedFunction>.GetAsyncEnumerator(CancellationToken cancellationToken)
{
return GetAllAsync(cancellationToken: cancellationToken).GetAsyncEnumerator(cancellationToken);
}
}
}
| 69.558333
| 502
| 0.711593
|
[
"MIT"
] |
KurnakovMaksim/azure-sdk-for-net
|
sdk/cosmosdb/Azure.ResourceManager.CosmosDB/src/Generated/SqlUserDefinedFunctionCollection.cs
| 25,041
|
C#
|
using System;
using System.Collections.Generic;
using System.Text;
namespace RawData
{
public class Car
{
public string Model { get; set; }
public Engine Engine { get; set; }
public Cargo Cargo { get; set; }
public Tire[] Tires { get; set; }
public Car(string model, Engine engine, Cargo cargo, Tire[] tires)
{
this.Model = model;
this.Engine = engine;
this.Cargo = cargo;
this.Tires = tires;
}
}
}
| 21.625
| 74
| 0.547206
|
[
"MIT"
] |
Siafarikas/SoftUni
|
Advanced/DefiningClasses2/RawData/Car.cs
| 521
|
C#
|
//
//
// THIS FILE HAS BEEN GENERATED. DO NOT MODIFY.
//
using System;
using System.Collections.Generic;
using byps;
namespace byps.test.api.remote
{
public sealed class BRequest_RemoteArrayTypes1dim_getShort : BMethodRequest, BSerializable
{
#region Execute
public override int getRemoteId() { return 123123; }
public override void execute(BRemote __byps__remote, BAsyncResultIF<Object> __byps__asyncResult) {
// checkpoint byps.gen.cs.GenApiClass:429
try {
RemoteArrayTypes1dim __byps__remoteT = (RemoteArrayTypes1dim)__byps__remote;
BAsyncResultSendMethod<short[]> __byps__outerResult = new BAsyncResultSendMethod<short[]>(__byps__asyncResult, new byps.test.api.BResult_2067161310());
__byps__remoteT.GetShort(BAsyncResultHelper.ToDelegate(__byps__outerResult));
} catch (Exception e) {
__byps__asyncResult.setAsyncResult(null, e);
}
}
#endregion
#region Fields
#endregion
public static readonly long serialVersionUID = 1373101854L;
} // end class
} // end namespace
| 25.829268
| 159
| 0.74221
|
[
"MIT"
] |
markusessigde/byps
|
csharp/bypstest-ser/src-ser/byps/test/api/remote/BRequest_RemoteArrayTypes1dim_getShort.cs
| 1,061
|
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/winhttp.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved.
using NUnit.Framework;
using System.Runtime.InteropServices;
namespace TerraFX.Interop.Windows.UnitTests;
/// <summary>Provides validation of the <see cref="WINHTTP_CONNECTION_INFO32" /> struct.</summary>
public static unsafe partial class WINHTTP_CONNECTION_INFO32Tests
{
/// <summary>Validates that the <see cref="WINHTTP_CONNECTION_INFO32" /> struct is blittable.</summary>
[Test]
public static void IsBlittableTest()
{
Assert.That(Marshal.SizeOf<WINHTTP_CONNECTION_INFO32>(), Is.EqualTo(sizeof(WINHTTP_CONNECTION_INFO32)));
}
/// <summary>Validates that the <see cref="WINHTTP_CONNECTION_INFO32" /> struct has the right <see cref="LayoutKind" />.</summary>
[Test]
public static void IsLayoutSequentialTest()
{
Assert.That(typeof(WINHTTP_CONNECTION_INFO32).IsLayoutSequential, Is.True);
}
/// <summary>Validates that the <see cref="WINHTTP_CONNECTION_INFO32" /> struct has the correct size.</summary>
[Test]
public static void SizeOfTest()
{
Assert.That(sizeof(WINHTTP_CONNECTION_INFO32), Is.EqualTo(260));
}
}
| 39.657143
| 145
| 0.73415
|
[
"MIT"
] |
IngmarBitter/terrafx.interop.windows
|
tests/Interop/Windows/Windows/um/winhttp/WINHTTP_CONNECTION_INFO32Tests.Manual.cs
| 1,390
|
C#
|
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#region Using directives
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Management.Automation;
using System.Threading;
#endregion
namespace Microsoft.Management.Infrastructure.CimCmdlets
{
/// <summary>
/// <para>
/// Async operation base class, it will issue async operation through
/// 1...* CimSession object(s), processing the async results, extended
/// pssemantics operations, and manage the lifecycle of created
/// CimSession object(s).
/// </para>
/// </summary>
internal abstract class CimAsyncOperation : IDisposable
{
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="CimAsyncOperation"/> class.
/// </summary>
protected CimAsyncOperation()
{
this.moreActionEvent = new ManualResetEventSlim(false);
this.actionQueue = new ConcurrentQueue<CimBaseAction>();
this._disposed = 0;
this.operationCount = 0;
}
#endregion
#region Event handler
/// <summary>
/// <para>
/// Handler used to handle new action event from
/// <seealso cref="CimSessionProxy"/> object.
/// </para>
/// </summary>
/// <param name="cimSession">
/// <seealso cref="CimSession"/> object raised the event
/// </param>
/// <param name="actionArgs">Event argument.</param>
protected void NewCmdletActionHandler(object cimSession, CmdletActionEventArgs actionArgs)
{
DebugHelper.WriteLogEx("Disposed {0}, action type = {1}", 0, this.Disposed, actionArgs.Action);
if (this.Disposed)
{
if (actionArgs.Action is CimSyncAction)
{
// unblock the thread waiting for response
(actionArgs.Action as CimSyncAction).OnComplete();
}
return;
}
bool isEmpty = this.actionQueue.IsEmpty;
this.actionQueue.Enqueue(actionArgs.Action);
if (isEmpty)
{
this.moreActionEvent.Set();
}
}
/// <summary>
/// <para>
/// Handler used to handle new operation event from
/// <seealso cref="CimSessionProxy"/> object.
/// </para>
/// </summary>
/// <param name="cimSession">
/// <seealso cref="CimSession"/> object raised the event.
/// </param>
/// <param name="actionArgs">Event argument.</param>
protected void OperationCreatedHandler(object cimSession, OperationEventArgs actionArgs)
{
DebugHelper.WriteLogEx();
lock (this.a_lock)
{
this.operationCount++;
}
}
/// <summary>
/// <para>
/// Handler used to handle operation deletion event from
/// <seealso cref="CimSessionProxy"/> object.
/// </para>
/// </summary>
/// <param name="cimSession">
/// <seealso cref="CimSession"/> object raised the event.
/// </param>
/// <param name="actionArgs">Event argument.</param>
protected void OperationDeletedHandler(object cimSession, OperationEventArgs actionArgs)
{
DebugHelper.WriteLogEx();
lock (this.a_lock)
{
this.operationCount--;
if (this.operationCount == 0)
{
this.moreActionEvent.Set();
}
}
}
#endregion
/// <summary>
/// <para>
/// process all actions in the action queue
/// </para>
/// </summary>
/// <param name="cmdletOperation">
/// Wrapper of cmdlet, <seealso cref="CmdletOperationBase"/> for details.
/// </param>
public void ProcessActions(CmdletOperationBase cmdletOperation)
{
if (!this.actionQueue.IsEmpty)
{
CimBaseAction action;
while (GetActionAndRemove(out action))
{
action.Execute(cmdletOperation);
if (this.Disposed)
{
break;
}
}
}
}
/// <summary>
/// <para>
/// Process remaining actions until all operations are completed or
/// current cmdlet is terminated by user.
/// </para>
/// </summary>
/// <param name="cmdletOperation">
/// Wrapper of cmdlet, <seealso cref="CmdletOperationBase"/> for details.
/// </param>
public void ProcessRemainActions(CmdletOperationBase cmdletOperation)
{
DebugHelper.WriteLogEx();
while (true)
{
ProcessActions(cmdletOperation);
if (!this.IsActive())
{
DebugHelper.WriteLogEx("Either disposed or all operations completed.", 2);
break;
}
try
{
this.moreActionEvent.Wait();
this.moreActionEvent.Reset();
}
catch (ObjectDisposedException ex)
{
// This might happen if this object is being disposed,
// while another thread is processing the remaining actions
DebugHelper.WriteLogEx("moreActionEvent was disposed: {0}.", 2, ex);
break;
}
}
ProcessActions(cmdletOperation);
}
#region helper methods
/// <summary>
/// <para>
/// Get action object from action queue.
/// </para>
/// </summary>
/// <param name="action">Next action to execute.</param>
/// <returns>True indicates there is an valid action, otherwise false.</returns>
protected bool GetActionAndRemove(out CimBaseAction action)
{
return this.actionQueue.TryDequeue(out action);
}
/// <summary>
/// <para>
/// Add temporary <seealso cref="CimSessionProxy"/> object to cache.
/// </para>
/// </summary>
/// <param name="sessionproxy">Cimsession wrapper object.</param>
protected void AddCimSessionProxy(CimSessionProxy sessionproxy)
{
lock (cimSessionProxyCacheLock)
{
if (this.cimSessionProxyCache == null)
{
this.cimSessionProxyCache = new List<CimSessionProxy>();
}
if (!this.cimSessionProxyCache.Contains(sessionproxy))
{
this.cimSessionProxyCache.Add(sessionproxy);
}
}
}
/// <summary>
/// <para>
/// Are there active operations?
/// </para>
/// </summary>
/// <returns>True for having active operations, otherwise false.</returns>
protected bool IsActive()
{
DebugHelper.WriteLogEx("Disposed {0}, Operation Count {1}", 2, this.Disposed, this.operationCount);
bool isActive = (!this.Disposed) && (this.operationCount > 0);
return isActive;
}
/// <summary>
/// Create <see cref="CimSessionProxy"/> object.
/// </summary>
/// <param name="session"></param>
protected CimSessionProxy CreateCimSessionProxy(CimSessionProxy originalProxy)
{
CimSessionProxy proxy = new(originalProxy);
this.SubscribeEventAndAddProxytoCache(proxy);
return proxy;
}
/// <summary>
/// Create <see cref="CimSessionProxy"/> object.
/// </summary>
/// <param name="session"></param>
protected CimSessionProxy CreateCimSessionProxy(CimSessionProxy originalProxy, bool passThru)
{
CimSessionProxy proxy = new CimSessionProxySetCimInstance(originalProxy, passThru);
this.SubscribeEventAndAddProxytoCache(proxy);
return proxy;
}
/// <summary>
/// Create <see cref="CimSessionProxy"/> object.
/// </summary>
/// <param name="session"></param>
protected CimSessionProxy CreateCimSessionProxy(CimSession session)
{
CimSessionProxy proxy = new(session);
this.SubscribeEventAndAddProxytoCache(proxy);
return proxy;
}
/// <summary>
/// Create <see cref="CimSessionProxy"/> object.
/// </summary>
/// <param name="session"></param>
protected CimSessionProxy CreateCimSessionProxy(CimSession session, bool passThru)
{
CimSessionProxy proxy = new CimSessionProxySetCimInstance(session, passThru);
this.SubscribeEventAndAddProxytoCache(proxy);
return proxy;
}
/// <summary>
/// Create <see cref="CimSessionProxy"/> object, and
/// add the proxy into cache.
/// </summary>
/// <param name="computerName"></param>
protected CimSessionProxy CreateCimSessionProxy(string computerName)
{
CimSessionProxy proxy = new(computerName);
this.SubscribeEventAndAddProxytoCache(proxy);
return proxy;
}
/// <summary>
/// Create <see cref="CimSessionProxy"/> object, and
/// add the proxy into cache.
/// </summary>
/// <param name="computerName"></param>
/// <param name="cimInstance"></param>
/// <returns></returns>
protected CimSessionProxy CreateCimSessionProxy(string computerName, CimInstance cimInstance)
{
CimSessionProxy proxy = new(computerName, cimInstance);
this.SubscribeEventAndAddProxytoCache(proxy);
return proxy;
}
/// <summary>
/// Create <see cref="CimSessionProxy"/> object, and
/// add the proxy into cache.
/// </summary>
/// <param name="computerName"></param>
/// <param name="cimInstance"></param>
/// <param name="passThru"></param>
protected CimSessionProxy CreateCimSessionProxy(string computerName, CimInstance cimInstance, bool passThru)
{
CimSessionProxy proxy = new CimSessionProxySetCimInstance(computerName, cimInstance, passThru);
this.SubscribeEventAndAddProxytoCache(proxy);
return proxy;
}
/// <summary>
/// Subscribe event from proxy and add proxy to cache.
/// </summary>
/// <param name="proxy"></param>
protected void SubscribeEventAndAddProxytoCache(CimSessionProxy proxy)
{
this.AddCimSessionProxy(proxy);
SubscribeToCimSessionProxyEvent(proxy);
}
/// <summary>
/// <para>
/// Subscribe to the events issued by <see cref="CimSessionProxy"/>.
/// </para>
/// </summary>
/// <param name="proxy"></param>
protected virtual void SubscribeToCimSessionProxyEvent(CimSessionProxy proxy)
{
DebugHelper.WriteLogEx();
proxy.OnNewCmdletAction += this.NewCmdletActionHandler;
proxy.OnOperationCreated += this.OperationCreatedHandler;
proxy.OnOperationDeleted += this.OperationDeletedHandler;
}
/// <summary>
/// Retrieve the base object out if wrapped in psobject.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
protected object GetBaseObject(object value)
{
PSObject psObject = value as PSObject;
if (psObject == null)
{
return value;
}
else
{
object baseObject = psObject.BaseObject;
var arrayObject = baseObject as object[];
if (arrayObject == null)
{
return baseObject;
}
else
{
object[] arraybaseObject = new object[arrayObject.Length];
for (int i = 0; i < arrayObject.Length; i++)
{
arraybaseObject[i] = GetBaseObject(arrayObject[i]);
}
return arraybaseObject;
}
}
}
/// <summary>
/// Retrieve the reference object or reference array object.
/// The returned object has to be either CimInstance or CImInstance[] type,
/// if not thrown exception.
/// </summary>
/// <param name="value"></param>
/// <param name="referenceType">Output the cimtype of the value, either Reference or ReferenceArray.</param>
/// <returns>The object.</returns>
protected object GetReferenceOrReferenceArrayObject(object value, ref CimType referenceType)
{
PSReference cimReference = value as PSReference;
if (cimReference != null)
{
object baseObject = GetBaseObject(cimReference.Value);
if (!(baseObject is CimInstance cimInstance))
{
return null;
}
referenceType = CimType.Reference;
return cimInstance;
}
else
{
object[] cimReferenceArray = value as object[];
if (cimReferenceArray == null)
{
return null;
}
else if (cimReferenceArray[0] is not PSReference)
{
return null;
}
CimInstance[] cimInstanceArray = new CimInstance[cimReferenceArray.Length];
for (int i = 0; i < cimReferenceArray.Length; i++)
{
if (!(cimReferenceArray[i] is PSReference tempCimReference))
{
return null;
}
object baseObject = GetBaseObject(tempCimReference.Value);
cimInstanceArray[i] = baseObject as CimInstance;
if (cimInstanceArray[i] == null)
{
return null;
}
}
referenceType = CimType.ReferenceArray;
return cimInstanceArray;
}
}
#endregion
#region IDisposable
/// <summary>
/// <para>
/// Indicates whether this object was disposed or not
/// </para>
/// </summary>
protected bool Disposed
{
get
{
return this._disposed == 1;
}
}
private int _disposed;
/// <summary>
/// <para>
/// Dispose() calls Dispose(true).
/// Implement IDisposable. Do not make this method virtual.
/// A derived class should not be able to override this method.
/// </para>
/// </summary>
public void Dispose()
{
Dispose(true);
// This object will be cleaned up by the Dispose method.
// Therefore, you should call GC.SuppressFinalize to
// take this object off the finalization queue
// and prevent finalization code for this object
// from executing a second time.
GC.SuppressFinalize(this);
}
/// <summary>
/// <para>
/// Dispose(bool disposing) executes in two distinct scenarios.
/// If disposing equals true, the method has been called directly
/// or indirectly by a user's code. Managed and unmanaged resources
/// can be disposed.
/// If disposing equals false, the method has been called by the
/// runtime from inside the finalizer and you should not reference
/// other objects. Only unmanaged resources can be disposed.
/// </para>
/// </summary>
/// <param name="disposing">Whether it is directly called.</param>
protected virtual void Dispose(bool disposing)
{
if (Interlocked.CompareExchange(ref this._disposed, 1, 0) == 0)
{
if (disposing)
{
// free managed resources
Cleanup();
}
// free native resources if there are any
}
}
/// <summary>
/// <para>
/// Clean up managed resources.
/// </para>
/// </summary>
private void Cleanup()
{
DebugHelper.WriteLogEx();
// unblock thread that waiting for more actions
this.moreActionEvent.Set();
CimBaseAction action;
while (GetActionAndRemove(out action))
{
DebugHelper.WriteLog("Action {0}", 2, action);
if (action is CimSyncAction)
{
// unblock the thread waiting for response
(action as CimSyncAction).OnComplete();
}
}
if (this.cimSessionProxyCache != null)
{
List<CimSessionProxy> temporaryProxy;
lock (this.cimSessionProxyCache)
{
temporaryProxy = new List<CimSessionProxy>(this.cimSessionProxyCache);
this.cimSessionProxyCache.Clear();
}
// clean up all proxy objects
foreach (CimSessionProxy proxy in temporaryProxy)
{
DebugHelper.WriteLog("Dispose proxy ", 2);
proxy.Dispose();
}
}
this.moreActionEvent.Dispose();
if (this.ackedEvent != null)
{
this.ackedEvent.Dispose();
}
DebugHelper.WriteLog("Cleanup complete.", 2);
}
#endregion
#region private members
/// <summary>
/// Lock object.
/// </summary>
private readonly object a_lock = new();
/// <summary>
/// Number of active operations.
/// </summary>
private uint operationCount;
/// <summary>
/// Event to notify ps thread that more action is available.
/// </summary>
private readonly ManualResetEventSlim moreActionEvent;
/// <summary>
/// The following is the definition of action queue.
/// The queue holding all actions to be executed in the context of either
/// ProcessRecord or EndProcessing.
/// </summary>
private readonly ConcurrentQueue<CimBaseAction> actionQueue;
/// <summary>
/// Lock object.
/// </summary>
private readonly object cimSessionProxyCacheLock = new();
/// <summary>
/// Cache all <see cref="CimSessionProxy"/> objects related to
/// the current operation.
/// </summary>
private List<CimSessionProxy> cimSessionProxyCache;
#endregion
#region protected members
/// <summary>
/// Event to notify ps thread that either a ACK message sent back
/// or a error happened. Currently only used by
/// <see cref="CimRegisterCimIndication"/>.
/// </summary>
protected ManualResetEventSlim ackedEvent;
#endregion
#region const strings
internal const string ComputerNameArgument = @"ComputerName";
internal const string CimSessionArgument = @"CimSession";
#endregion
}
}
| 33.600671
| 116
| 0.527764
|
[
"MIT"
] |
10088/PowerShell
|
src/Microsoft.Management.Infrastructure.CimCmdlets/CimAsyncOperation.cs
| 20,026
|
C#
|
namespace FastWfcDemoApp.Model
{
/// <summary>
/// Logging.
/// </summary>
public interface ILogger
{
/// <summary>
/// Logs a neutral message.
/// </summary>
/// <param name="msg">The message to log.</param>
void LogNeutral(string msg);
/// <summary>
/// Logs a success message.
/// </summary>
/// <param name="msg">The message to log.</param>
void LogSuccess(string msg);
/// <summary>
/// Logs a failure message.
/// </summary>
/// <param name="msg">The message to log.</param>
void LogFailure(string msg);
}
}
| 24.481481
| 57
| 0.506808
|
[
"MIT"
] |
ShyRed/fastwfcnet
|
FastWfcDemoApp/Model/ILogger.cs
| 663
|
C#
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System.Collections.Generic;
using Aliyun.Acs.Core;
namespace Aliyun.Acs.CCC.Model.V20170705
{
public class CreateUserResponse : AcsResponse
{
private string requestId;
private bool? success;
private string code;
private string message;
private int? httpStatusCode;
private string userId;
public string RequestId
{
get
{
return requestId;
}
set
{
requestId = value;
}
}
public bool? Success
{
get
{
return success;
}
set
{
success = value;
}
}
public string Code
{
get
{
return code;
}
set
{
code = value;
}
}
public string Message
{
get
{
return message;
}
set
{
message = value;
}
}
public int? HttpStatusCode
{
get
{
return httpStatusCode;
}
set
{
httpStatusCode = value;
}
}
public string UserId
{
get
{
return userId;
}
set
{
userId = value;
}
}
}
}
| 16.663717
| 63
| 0.615507
|
[
"Apache-2.0"
] |
AxiosCros/aliyun-openapi-net-sdk
|
aliyun-net-sdk-ccc/CCC/Model/V20170705/CreateUserResponse.cs
| 1,883
|
C#
|
using System;
using System.Collections.Generic;
namespace _12.MasterNumbersLast
{
public class Master
{
public static void Main()
{
int n = int.Parse(Console.ReadLine());
List<int> listDiv7 = new List<int>();
if (ContainsEvenDigit(n))
{
Console.WriteLine(string.Join(" ", listDiv7));
}
//for (int i = 0; i <= n; i++)
//{
// if (ContainsEvenDigit(i) == true)
// {
// Console.WriteLine(i);
// }
//}
}
static bool IsPalindrome(string n)
{
for (int i = 0; i < n.Length / 2; i++)
{
if (n[i] != n[n.Length - 1 - i])
{
return false;
}
}
return true;
}
static bool ContainsEvenDigit(int n)
{
bool isFound = false;
for (int i = 1; i <= n; i++)
{
var number = i;
int counter = 0;
while (number > 0)
{
var digit = number % 10;
if (digit % 2 == 0)
{
counter++;
}
number = number / 10;
}
if (counter > 0)
{
isFound = true;
// listDiv7.Add(i);
}
}
if (isFound)
{
return true;
}
else
{
return false;
}
}
static bool SumOfDigits(int n)
{
for (int i = 0; i <= n; i++)
{
var number = i;
var sum = 0;
while (number > 0)
{
var digit = number % 10;
number = number / 10;
sum += digit;
}
if (sum % 7 != 0)
{
return false;
}
}
return true;
}
}
}
//&& (SumOfDigits(i) == true) &&(IsPalindrome(i.ToString()) == true)
// (ContainsEvenDigit(i) == true))
| 23.303922
| 68
| 0.313
|
[
"MIT"
] |
paykova/TEST
|
ProgrammingFundamentals/MethodsEX/12.MasterNumbersLast/Master.cs
| 2,379
|
C#
|
using System;
namespace Mapsui.ArcGIS.ImageServiceProvider
{
public class TimeInfo
{
public string? startTimeField { get; set; }
public string? endTimeField { get; set; }
public long[]? timeExtent { get; set; }
public TimeReference? timeReference { get; set; }
public DateTime? StartDate => timeExtent?.Length == 2 ? ConvertUnixTimeStamp(timeExtent[0]) : ConvertUnixTimeStamp(0);
public DateTime? EndDate => timeExtent?.Length == 2 ? ConvertUnixTimeStamp(timeExtent[1]) : ConvertUnixTimeStamp(0);
public static DateTime? ConvertUnixTimeStamp(long unixTimeStamp)
{
return new DateTime(1970, 1, 1, 0, 0, 0).AddMilliseconds(unixTimeStamp);
}
}
}
| 33.772727
| 126
| 0.659489
|
[
"MIT"
] |
rafntor/Mapsui
|
Mapsui.ArcGIS/ImageServiceProvider/TimeInfo.cs
| 743
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Routing;
using Microsoft.Framework.DependencyInjection;
namespace OnlineAPIBuilder
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
}
// This method gets called by a runtime.
// Use this method to add services to the container
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
// Uncomment the following line to add Web API services which makes it easier to port Web API 2 controllers.
// You will also need to add the Microsoft.AspNet.Mvc.WebApiCompatShim package to the 'dependencies' section of project.json.
// services.AddWebApiConventions();
}
// Configure is called after ConfigureServices is called.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
// Configure the HTTP request pipeline.
app.UseStaticFiles();
// Add MVC to the request pipeline.
app.UseMvc();
// Add the following route for porting Web API 2 controllers.
// routes.MapWebApiRoute("DefaultApi", "api/{controller}/{id?}");
}
}
}
| 33.857143
| 137
| 0.66315
|
[
"MIT"
] |
OnlineAPIGenerator/OnlineAPIBuilder
|
src/OnlineAPIBuilder/Startup.cs
| 1,424
|
C#
|
/*
* Copyright (c) 2018 THL A29 Limited, a Tencent company. 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.
*/
namespace TencentCloud.Cfw.V20190904.Models
{
using Newtonsoft.Json;
using System.Collections.Generic;
using TencentCloud.Common;
public class RuleInfoData : AbstractModel
{
/// <summary>
/// 执行顺序
/// </summary>
[JsonProperty("OrderIndex")]
public ulong? OrderIndex{ get; set; }
/// <summary>
/// 访问源
/// </summary>
[JsonProperty("SourceIp")]
public string SourceIp{ get; set; }
/// <summary>
/// 访问目的
/// </summary>
[JsonProperty("TargetIp")]
public string TargetIp{ get; set; }
/// <summary>
/// 协议
/// </summary>
[JsonProperty("Protocol")]
public string Protocol{ get; set; }
/// <summary>
/// 策略
/// </summary>
[JsonProperty("Strategy")]
public string Strategy{ get; set; }
/// <summary>
/// 访问源类型,1是IP,3是域名,4是IP地址模版,5是域名地址模版
/// </summary>
[JsonProperty("SourceType")]
public ulong? SourceType{ get; set; }
/// <summary>
/// 方向,0:出站,1:入站
/// </summary>
[JsonProperty("Direction")]
public ulong? Direction{ get; set; }
/// <summary>
/// 描述
/// </summary>
[JsonProperty("Detail")]
public string Detail{ get; set; }
/// <summary>
/// 访问目的类型,1是IP,3是域名,4是IP地址模版,5是域名地址模版
/// </summary>
[JsonProperty("TargetType")]
public ulong? TargetType{ get; set; }
/// <summary>
/// 端口
/// </summary>
[JsonProperty("Port")]
public string Port{ get; set; }
/// <summary>
/// id值
/// </summary>
[JsonProperty("Id")]
public ulong? Id{ get; set; }
/// <summary>
/// 日志id,从告警处创建必传,其它为空
/// </summary>
[JsonProperty("LogId")]
public string LogId{ get; set; }
/// <summary>
/// 城市Code
/// </summary>
[JsonProperty("City")]
public ulong? City{ get; set; }
/// <summary>
/// 国家Code
/// </summary>
[JsonProperty("Country")]
public ulong? Country{ get; set; }
/// <summary>
/// 云厂商,支持多个,以逗号分隔, 1:腾讯云(仅中国香港及海外),2:阿里云,3:亚马逊云,4:华为云,5:微软云
/// </summary>
[JsonProperty("CloudCode")]
public string CloudCode{ get; set; }
/// <summary>
/// 是否为地域
/// </summary>
[JsonProperty("IsRegion")]
public ulong? IsRegion{ get; set; }
/// <summary>
/// 城市名
/// </summary>
[JsonProperty("CityName")]
public string CityName{ get; set; }
/// <summary>
/// 国家名
/// </summary>
[JsonProperty("CountryName")]
public string CountryName{ get; set; }
/// <summary>
/// For internal usage only. DO NOT USE IT.
/// </summary>
public override void ToMap(Dictionary<string, string> map, string prefix)
{
this.SetParamSimple(map, prefix + "OrderIndex", this.OrderIndex);
this.SetParamSimple(map, prefix + "SourceIp", this.SourceIp);
this.SetParamSimple(map, prefix + "TargetIp", this.TargetIp);
this.SetParamSimple(map, prefix + "Protocol", this.Protocol);
this.SetParamSimple(map, prefix + "Strategy", this.Strategy);
this.SetParamSimple(map, prefix + "SourceType", this.SourceType);
this.SetParamSimple(map, prefix + "Direction", this.Direction);
this.SetParamSimple(map, prefix + "Detail", this.Detail);
this.SetParamSimple(map, prefix + "TargetType", this.TargetType);
this.SetParamSimple(map, prefix + "Port", this.Port);
this.SetParamSimple(map, prefix + "Id", this.Id);
this.SetParamSimple(map, prefix + "LogId", this.LogId);
this.SetParamSimple(map, prefix + "City", this.City);
this.SetParamSimple(map, prefix + "Country", this.Country);
this.SetParamSimple(map, prefix + "CloudCode", this.CloudCode);
this.SetParamSimple(map, prefix + "IsRegion", this.IsRegion);
this.SetParamSimple(map, prefix + "CityName", this.CityName);
this.SetParamSimple(map, prefix + "CountryName", this.CountryName);
}
}
}
| 30.920245
| 81
| 0.550794
|
[
"Apache-2.0"
] |
tianhuangtencent/tencentcloud-sdk-dotnet
|
TencentCloud/Cfw/V20190904/Models/RuleInfoData.cs
| 5,346
|
C#
|
using System;
using System.Globalization;
using System.Windows.Data;
using FamilyExpenses.Model;
namespace FamilyExpenses.ViewModels.Converters
{
internal sealed class ProductInfoConverter
: IMultiValueConverter
{
#region IMultiValueConverter Members
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
try
{
return Tuple.Create((string)values[0], (ProductType)Enum.Parse(typeof(ProductType), values[1].ToString()), (Producer)values[2]);
}
catch
{
return null;
}
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
Tuple<string, string, Producer> personInfo = value as Tuple<string, string, Producer>;
if (personInfo != null)
return new object[] { personInfo.Item1, personInfo.Item2.ToString(), personInfo.Item3 };
else
return new object[] { string.Empty, ProductType.Electric.ToString(), null };
}
#endregion
}
}
| 30.5
| 132
| 0.729508
|
[
"MIT"
] |
Andrei15193/Laboratoare-Facultate
|
Semestrul5/DS/Project/FamilyExpenses/ViewModels/Converters/ProductInfoConverter.cs
| 978
|
C#
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit.Abstractions;
namespace Microsoft.Diagnostic.TestHelpers
{
/// <summary>
/// An implementation of ITestOutputHelper that adds one indent level to
/// the start of each line
/// </summary>
public class IndentedTestOutputHelper : ITestOutputHelper
{
readonly string _indentText;
readonly ITestOutputHelper _output;
public IndentedTestOutputHelper(ITestOutputHelper innerOutput, string indentText = " ")
{
_output = innerOutput;
_indentText = indentText;
}
public void WriteLine(string message)
{
_output.WriteLine(_indentText + message);
}
public void WriteLine(string format, params object[] args)
{
_output.WriteLine(_indentText + format, args);
}
}
}
| 29.714286
| 98
| 0.653846
|
[
"MIT"
] |
AzureMentor/diagnostics
|
src/Microsoft.Diagnostic.TestHelpers/IndentedTestOutputHelper.cs
| 1,042
|
C#
|
using System;
using System.Diagnostics;
using System.Text;
using HANDLE = System.IntPtr;
namespace Community.CsharpSqlite
{
public partial class Sqlite3
{
/*
** 2006 June 7
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains code used to dynamically load extensions into
** the SQLite library.
*************************************************************************
** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
** C#-SQLite is an independent reimplementation of the SQLite software library
**
** SQLITE_SOURCE_ID: 2011-05-19 13:26:54 ed1da510a239ea767a01dc332b667119fa3c908e
**
*************************************************************************
*/
#if !SQLITE_CORE
//#define SQLITE_CORE 1 /* Disable the API redefinition in sqlite3ext.h */
private const int SQLITE_CORE = 1;
#endif
//#include "sqlite3ext.h"
//#include "sqliteInt.h"
//#include <string.h>
#if !SQLITE_OMIT_LOAD_EXTENSION
/*
** Some API routines are omitted when various features are
** excluded from a build of SQLite. Substitute a NULL pointer
** for any missing APIs.
*/
#if !SQLITE_ENABLE_COLUMN_METADATA
//# define sqlite3_column_database_name 0
//# define sqlite3_column_database_name16 0
//# define sqlite3_column_table_name 0
//# define sqlite3_column_table_name16 0
//# define sqlite3_column_origin_name 0
//# define sqlite3_column_origin_name16 0
//# define sqlite3_table_column_metadata 0
#endif
#if SQLITE_OMIT_AUTHORIZATION
//# define sqlite3_set_authorizer 0
#endif
#if SQLITE_OMIT_UTF16
//# define sqlite3_bind_text16 0
//# define sqlite3_collation_needed16 0
//# define sqlite3_column_decltype16 0
//# define sqlite3_column_name16 0
//# define sqlite3_column_text16 0
//# define sqlite3_complete16 0
//# define sqlite3_create_collation16 0
//# define sqlite3_create_function16 0
//# define sqlite3_errmsg16 0
private static string sqlite3_errmsg16(sqlite3 db)
{
return "";
}
//# define sqlite3_open16 0
//# define sqlite3_prepare16 0
//# define sqlite3_prepare16_v2 0
//# define sqlite3_result_error16 0
//# define sqlite3_result_text16 0
private static void sqlite3_result_text16(sqlite3_context pCtx, string z, int n, dxDel xDel)
{
}
//# define sqlite3_result_text16be 0
//# define sqlite3_result_text16le 0
//# define sqlite3_value_text16 0
//# define sqlite3_value_text16be 0
//# define sqlite3_value_text16le 0
//# define sqlite3_column_database_name16 0
//# define sqlite3_column_table_name16 0
//# define sqlite3_column_origin_name16 0
#endif
#if SQLITE_OMIT_COMPLETE
//# define sqlite3_complete 0
//# define sqlite3_complete16 0
#endif
#if SQLITE_OMIT_DECLTYPE
//# define sqlite3_column_decltype16 0
//# define sqlite3_column_decltype 0
#endif
#if SQLITE_OMIT_PROGRESS_CALLBACK
//# define sqlite3_progress_handler 0
static void sqlite3_progress_handler (sqlite3 db, int nOps, dxProgress xProgress, object pArg){}
#endif
#if SQLITE_OMIT_VIRTUALTABLE
//# define sqlite3_create_module 0
//# define sqlite3_create_module_v2 0
//# define sqlite3_declare_vtab 0
#endif
#if SQLITE_OMIT_SHARED_CACHE
//# define sqlite3_enable_shared_cache 0
#endif
#if SQLITE_OMIT_TRACE
//# define sqlite3_profile 0
//# define sqlite3_trace 0
#endif
#if SQLITE_OMIT_GET_TABLE
//# define //sqlite3_free_table 0
static public int sqlite3_free_table(ref string[] pazResult)
{
pazResult = null; return 0;
}
static public int sqlite3_get_table(
sqlite3 db, /* An open database */
string zSql, /* SQL to be evaluated */
ref string[] pazResult, /* Results of the query */
ref int pnRow, /* Number of result rows written here */
object dummy,
ref string pzErrmsg /* Error msg written here */
)
{
int iDummy = 0;
return sqlite3_get_table(db, zSql, ref pazResult, ref pnRow, ref iDummy, ref pzErrmsg);
}
//# define sqlite3_get_table 0
static public int sqlite3_get_table(
sqlite3 db, /* An open database */
string zSql, /* SQL to be evaluated */
ref string[] pazResult, /* Results of the query */
ref int pnRow, /* Number of result rows written here */
ref int pnColumn, /* Number of result columns written here */
ref string pzErrmsg /* Error msg written here */
)
{
return 0;
}
#endif
#if SQLITE_OMIT_INCRBLOB
//#define sqlite3_bind_zeroblob 0
//#define sqlite3_blob_bytes 0
//#define sqlite3_blob_close 0
//#define sqlite3_blob_open 0
//#define sqlite3_blob_read 0
//#define sqlite3_blob_write 0
#endif
/*
** The following structure contains pointers to all SQLite API routines.
** A pointer to this structure is passed into extensions when they are
** loaded so that the extension can make calls back into the SQLite
** library.
**
** When adding new APIs, add them to the bottom of this structure
** in order to preserve backwards compatibility.
**
** Extensions that use newer APIs should first call the
** sqlite3_libversion_number() to make sure that the API they
** intend to use is supported by the library. Extensions should
** also check to make sure that the pointer to the function is
** not NULL before calling it.
*/
public class sqlite3_api_routines
{
public sqlite3 context_db_handle;
};
private static sqlite3_api_routines sqlite3Apis = new sqlite3_api_routines();
//{
// sqlite3_aggregate_context,
#if !SQLITE_OMIT_DEPRECATED
/ sqlite3_aggregate_count,
#else
// 0,
#endif
// sqlite3_bind_blob,
// sqlite3_bind_double,
// sqlite3_bind_int,
// sqlite3_bind_int64,
// sqlite3_bind_null,
// sqlite3_bind_parameter_count,
// sqlite3_bind_parameter_index,
// sqlite3_bind_parameter_name,
// sqlite3_bind_text,
// sqlite3_bind_text16,
// sqlite3_bind_value,
// sqlite3_busy_handler,
// sqlite3_busy_timeout,
// sqlite3_changes,
// sqlite3_close,
// sqlite3_collation_needed,
// sqlite3_collation_needed16,
// sqlite3_column_blob,
// sqlite3_column_bytes,
// sqlite3_column_bytes16,
// sqlite3_column_count,
// sqlite3_column_database_name,
// sqlite3_column_database_name16,
// sqlite3_column_decltype,
// sqlite3_column_decltype16,
// sqlite3_column_double,
// sqlite3_column_int,
// sqlite3_column_int64,
// sqlite3_column_name,
// sqlite3_column_name16,
// sqlite3_column_origin_name,
// sqlite3_column_origin_name16,
// sqlite3_column_table_name,
// sqlite3_column_table_name16,
// sqlite3_column_text,
// sqlite3_column_text16,
// sqlite3_column_type,
// sqlite3_column_value,
// sqlite3_commit_hook,
// sqlite3_complete,
// sqlite3_complete16,
// sqlite3_create_collation,
// sqlite3_create_collation16,
// sqlite3_create_function,
// sqlite3_create_function16,
// sqlite3_create_module,
// sqlite3_data_count,
// sqlite3_db_handle,
// sqlite3_declare_vtab,
// sqlite3_enable_shared_cache,
// sqlite3_errcode,
// sqlite3_errmsg,
// sqlite3_errmsg16,
// sqlite3_exec,
#if !SQLITE_OMIT_DEPRECATED
//sqlite3_expired,
#else
//0,
#endif
// sqlite3_finalize,
// //sqlite3_free,
// //sqlite3_free_table,
// sqlite3_get_autocommit,
// sqlite3_get_auxdata,
// sqlite3_get_table,
// 0, /* Was sqlite3_global_recover(), but that function is deprecated */
// sqlite3_interrupt,
// sqlite3_last_insert_rowid,
// sqlite3_libversion,
// sqlite3_libversion_number,
// sqlite3_malloc,
// sqlite3_mprintf,
// sqlite3_open,
// sqlite3_open16,
// sqlite3_prepare,
// sqlite3_prepare16,
// sqlite3_profile,
// sqlite3_progress_handler,
// sqlite3_realloc,
// sqlite3_reset,
// sqlite3_result_blob,
// sqlite3_result_double,
// sqlite3_result_error,
// sqlite3_result_error16,
// sqlite3_result_int,
// sqlite3_result_int64,
// sqlite3_result_null,
// sqlite3_result_text,
// sqlite3_result_text16,
// sqlite3_result_text16be,
// sqlite3_result_text16le,
// sqlite3_result_value,
// sqlite3_rollback_hook,
// sqlite3_set_authorizer,
// sqlite3_set_auxdata,
// sqlite3_snprintf,
// sqlite3_step,
// sqlite3_table_column_metadata,
#if !SQLITE_OMIT_DEPRECATED
//sqlite3_thread_cleanup,
#else
// 0,
#endif
// sqlite3_total_changes,
// sqlite3_trace,
#if !SQLITE_OMIT_DEPRECATED
//sqlite3_transfer_bindings,
#else
// 0,
#endif
// sqlite3_update_hook,
// sqlite3_user_data,
// sqlite3_value_blob,
// sqlite3_value_bytes,
// sqlite3_value_bytes16,
// sqlite3_value_double,
// sqlite3_value_int,
// sqlite3_value_int64,
// sqlite3_value_numeric_type,
// sqlite3_value_text,
// sqlite3_value_text16,
// sqlite3_value_text16be,
// sqlite3_value_text16le,
// sqlite3_value_type,
// sqlite3_vmprintf,
// /*
// ** The original API set ends here. All extensions can call any
// ** of the APIs above provided that the pointer is not NULL. But
// ** before calling APIs that follow, extension should check the
// ** sqlite3_libversion_number() to make sure they are dealing with
// ** a library that is new enough to support that API.
// *************************************************************************
// */
// sqlite3_overload_function,
// /*
// ** Added after 3.3.13
// */
// sqlite3_prepare_v2,
// sqlite3_prepare16_v2,
// sqlite3_clear_bindings,
// /*
// ** Added for 3.4.1
// */
// sqlite3_create_module_v2,
// /*
// ** Added for 3.5.0
// */
// sqlite3_bind_zeroblob,
// sqlite3_blob_bytes,
// sqlite3_blob_close,
// sqlite3_blob_open,
// sqlite3_blob_read,
// sqlite3_blob_write,
// sqlite3_create_collation_v2,
// sqlite3_file_control,
// sqlite3_memory_highwater,
// sqlite3_memory_used,
#if SQLITE_MUTEX_OMIT
// 0,
// 0,
// 0,
// 0,
// 0,
#else
// sqlite3MutexAlloc,
// sqlite3_mutex_enter,
// sqlite3_mutex_free,
// sqlite3_mutex_leave,
// sqlite3_mutex_try,
#endif
// sqlite3_open_v2,
// sqlite3_release_memory,
// sqlite3_result_error_nomem,
// sqlite3_result_error_toobig,
// sqlite3_sleep,
// sqlite3_soft_heap_limit,
// sqlite3_vfs_find,
// sqlite3_vfs_register,
// sqlite3_vfs_unregister,
// /*
// ** Added for 3.5.8
// */
// sqlite3_threadsafe,
// sqlite3_result_zeroblob,
// sqlite3_result_error_code,
// sqlite3_test_control,
// sqlite3_randomness,
// sqlite3_context_db_handle,
// /*
// ** Added for 3.6.0
// */
// sqlite3_extended_result_codes,
// sqlite3_limit,
// sqlite3_next_stmt,
// sqlite3_sql,
// sqlite3_status,
// /*
// ** Added for 3.7.4
// */
// sqlite3_backup_finish,
// sqlite3_backup_init,
// sqlite3_backup_pagecount,
// sqlite3_backup_remaining,
// sqlite3_backup_step,
//#if !SQLITE_OMIT_COMPILEOPTION_DIAGS
// sqlite3_compileoption_get,
// sqlite3_compileoption_used,
//#else
// 0,
// 0,
//#endif
// sqlite3_create_function_v2,
// sqlite3_db_config,
// sqlite3_db_mutex,
// sqlite3_db_status,
// sqlite3_extended_errcode,
// sqlite3_log,
// sqlite3_soft_heap_limit64,
// sqlite3_sourceid,
// sqlite3_stmt_status,
// sqlite3_strnicmp,
//#if SQLITE_ENABLE_UNLOCK_NOTIFY
// sqlite3_unlock_notify,
//#else
// 0,
//#endif
//#if !SQLITE_OMIT_WAL
// sqlite3_wal_autocheckpoint,
// sqlite3_wal_checkpoint,
// sqlite3_wal_hook,
//#else
// 0,
// 0,
// 0,
//#endif
//};
/*
** Attempt to load an SQLite extension library contained in the file
** zFile. The entry point is zProc. zProc may be 0 in which case a
** default entry point name (sqlite3_extension_init) is used. Use
** of the default name is recommended.
**
** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
**
** If an error occurs and pzErrMsg is not 0, then fill pzErrMsg with
** error message text. The calling function should free this memory
** by calling sqlite3DbFree(db, ).
*/
private static int sqlite3LoadExtension(
sqlite3 db, /* Load the extension into this database connection */
string zFile, /* Name of the shared library containing extension */
string zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
ref string pzErrMsg /* Put error message here if not 0 */
)
{
sqlite3_vfs pVfs = db.pVfs;
HANDLE handle;
dxInit xInit; //int (*xInit)(sqlite3*,char**,const sqlite3_api_routines);
StringBuilder zErrmsg = new StringBuilder(100);
//object aHandle;
const int nMsg = 300;
if (pzErrMsg != null)
pzErrMsg = null;
/* Ticket #1863. To avoid a creating security problems for older
** applications that relink against newer versions of SQLite, the
** ability to run load_extension is turned off by default. One
** must call sqlite3_enable_load_extension() to turn on extension
** loading. Otherwise you get the following error.
*/
if ((db.flags & SQLITE_LoadExtension) == 0)
{
//if( pzErrMsg != null){
pzErrMsg = sqlite3_mprintf("not authorized");
//}
return SQLITE_ERROR;
}
if (zProc == null || zProc == "")
{
zProc = "sqlite3_extension_init";
}
handle = sqlite3OsDlOpen(pVfs, zFile);
if (handle == IntPtr.Zero)
{
// if( pzErrMsg ){
pzErrMsg = "";//*pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
//if( zErrmsg !=null){
sqlite3_snprintf(nMsg, zErrmsg,
"unable to open shared library [%s]", zFile);
sqlite3OsDlError(pVfs, nMsg - 1, zErrmsg.ToString());
return SQLITE_ERROR;
}
//xInit = (int()(sqlite3*,char**,const sqlite3_api_routines))
// sqlite3OsDlSym(pVfs, handle, zProc);
xInit = (dxInit)sqlite3OsDlSym(pVfs, handle, ref zProc);
Debugger.Break(); // TODO --
//if( xInit==0 ){
// if( pzErrMsg ){
// *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
// if( zErrmsg ){
// sqlite3_snprintf(nMsg, zErrmsg,
// "no entry point [%s] in shared library [%s]", zProc,zFile);
// sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
// }
// sqlite3OsDlClose(pVfs, handle);
// }
// return SQLITE_ERROR;
// }else if( xInit(db, ref zErrmsg, sqlite3Apis) ){
//// if( pzErrMsg !=null){
// pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
// //}
// sqlite3DbFree(db,ref zErrmsg);
// sqlite3OsDlClose(pVfs, ref handle);
// return SQLITE_ERROR;
// }
// /* Append the new shared library handle to the db.aExtension array. */
// aHandle = sqlite3DbMallocZero(db, sizeof(handle)*db.nExtension+1);
// if( aHandle==null ){
// return SQLITE_NOMEM;
// }
// if( db.nExtension>0 ){
// memcpy(aHandle, db.aExtension, sizeof(handle)*(db.nExtension));
// }
// sqlite3DbFree(db,ref db.aExtension);
// db.aExtension = aHandle;
// db.aExtension[db.nExtension++] = handle;
return SQLITE_OK;
}
static public int sqlite3_load_extension(
sqlite3 db, /* Load the extension into this database connection */
string zFile, /* Name of the shared library containing extension */
string zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
ref string pzErrMsg /* Put error message here if not 0 */
)
{
int rc;
sqlite3_mutex_enter(db.mutex);
rc = sqlite3LoadExtension(db, zFile, zProc, ref pzErrMsg);
rc = sqlite3ApiExit(db, rc);
sqlite3_mutex_leave(db.mutex);
return rc;
}
/*
** Call this routine when the database connection is closing in order
** to clean up loaded extensions
*/
private static void sqlite3CloseExtensions(sqlite3 db)
{
int i;
Debug.Assert(sqlite3_mutex_held(db.mutex));
for (i = 0; i < db.nExtension; i++)
{
sqlite3OsDlClose(db.pVfs, (HANDLE)db.aExtension[i]);
}
sqlite3DbFree(db, ref db.aExtension);
}
/*
** Enable or disable extension loading. Extension loading is disabled by
** default so as not to open security holes in older applications.
*/
static public int sqlite3_enable_load_extension(sqlite3 db, int onoff)
{
sqlite3_mutex_enter(db.mutex);
if (onoff != 0)
{
db.flags |= SQLITE_LoadExtension;
}
else
{
db.flags &= ~SQLITE_LoadExtension;
}
sqlite3_mutex_leave(db.mutex);
return SQLITE_OK;
}
#endif //* SQLITE_OMIT_LOAD_EXTENSION */
/*
** The auto-extension code added regardless of whether or not extension
** loading is supported. We need a dummy sqlite3Apis pointer for that
** code if regular extension loading is not available. This is that
** dummy pointer.
*/
#if SQLITE_OMIT_LOAD_EXTENSION
const sqlite3_api_routines sqlite3Apis = null;
#endif
/*
** The following object holds the list of automatically loaded
** extensions.
**
** This list is shared across threads. The SQLITE_MUTEX_STATIC_MASTER
** mutex must be held while accessing this list.
*/
//typedef struct sqlite3AutoExtList sqlite3AutoExtList;
public class sqlite3AutoExtList
{
public int nExt = 0; /* Number of entries in aExt[] */
public dxInit[] aExt = null; /* Pointers to the extension init functions */
public sqlite3AutoExtList(int nExt, dxInit[] aExt)
{
this.nExt = nExt;
this.aExt = aExt;
}
}
private static sqlite3AutoExtList sqlite3Autoext = new sqlite3AutoExtList(0, null);
/* The "wsdAutoext" macro will resolve to the autoextension
** state vector. If writable static data is unsupported on the target,
** we have to locate the state vector at run-time. In the more common
** case where writable static data is supported, wsdStat can refer directly
** to the "sqlite3Autoext" state vector declared above.
*/
#if SQLITE_OMIT_WSD
//# define wsdAutoextInit \
sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
//# define wsdAutoext x[0]
#else
//# define wsdAutoextInit
private static void wsdAutoextInit()
{
}
//# define wsdAutoext sqlite3Autoext
private static sqlite3AutoExtList wsdAutoext = sqlite3Autoext;
#endif
/*
** Register a statically linked extension that is automatically
** loaded by every new database connection.
*/
private static int sqlite3_auto_extension(dxInit xInit)
{
int rc = SQLITE_OK;
#if !SQLITE_OMIT_AUTOINIT
rc = sqlite3_initialize();
if (rc != 0)
{
return rc;
}
else
#endif
{
int i;
#if SQLITE_THREADSAFE
sqlite3_mutex mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
#else
sqlite3_mutex mutex = sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MASTER );
#endif
wsdAutoextInit();
sqlite3_mutex_enter(mutex);
for (i = 0; i < wsdAutoext.nExt; i++)
{
if (wsdAutoext.aExt[i] == xInit)
break;
}
//if( i==wsdAutoext.nExt ){
// int nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
// void **aNew;
// aNew = sqlite3_realloc(wsdAutoext.aExt, nByte);
// if( aNew==0 ){
// rc = SQLITE_NOMEM;
// }else{
Array.Resize(ref wsdAutoext.aExt, wsdAutoext.nExt + 1);// wsdAutoext.aExt = aNew;
wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
wsdAutoext.nExt++;
//}
sqlite3_mutex_leave(mutex);
Debug.Assert((rc & 0xff) == rc);
return rc;
}
}
/*
** Reset the automatic extension loading mechanism.
*/
private static void sqlite3_reset_auto_extension()
{
#if !SQLITE_OMIT_AUTOINIT
if (sqlite3_initialize() == SQLITE_OK)
#endif
{
#if SQLITE_THREADSAFE
sqlite3_mutex mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
#else
sqlite3_mutex mutex = sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MASTER );
#endif
wsdAutoextInit();
sqlite3_mutex_enter(mutex);
#if SQLITE_OMIT_WSD
//sqlite3_free( ref wsdAutoext.aExt );
wsdAutoext.aExt = null;
wsdAutoext.nExt = 0;
#else
//sqlite3_free( ref sqlite3Autoext.aExt );
sqlite3Autoext.aExt = null;
sqlite3Autoext.nExt = 0;
#endif
sqlite3_mutex_leave(mutex);
}
}
/*
** Load all automatic extensions.
**
** If anything goes wrong, set an error in the database connection.
*/
private static void sqlite3AutoLoadExtensions(sqlite3 db)
{
int i;
bool go = true;
dxInit xInit;//)(sqlite3*,char**,const sqlite3_api_routines);
wsdAutoextInit();
#if SQLITE_OMIT_WSD
if ( wsdAutoext.nExt == 0 )
#else
if (sqlite3Autoext.nExt == 0)
#endif
{
/* Common case: early out without every having to acquire a mutex */
return;
}
for (i = 0; go; i++)
{
string zErrmsg = "";
#if SQLITE_THREADSAFE
sqlite3_mutex mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
#else
sqlite3_mutex mutex = sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MASTER );
#endif
sqlite3_mutex_enter(mutex);
if (i >= wsdAutoext.nExt)
{
xInit = null;
go = false;
}
else
{
xInit = (dxInit)
wsdAutoext.aExt[i];
}
sqlite3_mutex_leave(mutex);
zErrmsg = "";
if (xInit != null && xInit(db, ref zErrmsg, (sqlite3_api_routines)sqlite3Apis) != 0)
{
sqlite3Error(db, SQLITE_ERROR,
"automatic extension loading failed: %s", zErrmsg);
go = false;
}
sqlite3DbFree(db, ref zErrmsg);
}
}
}
}
| 28.098845
| 102
| 0.665311
|
[
"BSD-2-Clause"
] |
Banbury/MatterControl
|
Community.CsharpSqlite/src/loadext_c.cs
| 21,889
|
C#
|
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace MvcTemplate.Resources.Permission.Area {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
public class Titles {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Titles() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("MvcTemplate.Resources.Permission.Area.Titles", typeof(Titles).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized string similar to Administration.
/// </summary>
public static string Administration {
get {
return ResourceManager.GetString("Administration", resourceCulture);
}
}
}
}
| 42.383562
| 186
| 0.604719
|
[
"MIT"
] |
DevX-Realtobiz/MVC6.Template
|
src/MvcTemplate.Resources/Permission/Area/Titles.Designer.cs
| 3,096
|
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 quicksight-2018-04-01.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.QuickSight.Model
{
/// <summary>
/// This is the response object from the DescribeUser operation.
/// </summary>
public partial class DescribeUserResponse : AmazonWebServiceResponse
{
private string _requestId;
private int? _status;
private User _user;
/// <summary>
/// Gets and sets the property RequestId.
/// <para>
/// The AWS request ID for this operation.
/// </para>
/// </summary>
public string RequestId
{
get { return this._requestId; }
set { this._requestId = value; }
}
// Check to see if RequestId property is set
internal bool IsSetRequestId()
{
return this._requestId != null;
}
/// <summary>
/// Gets and sets the property Status.
/// <para>
/// The http status of the request.
/// </para>
/// </summary>
public int Status
{
get { return this._status.GetValueOrDefault(); }
set { this._status = value; }
}
// Check to see if Status property is set
internal bool IsSetStatus()
{
return this._status.HasValue;
}
/// <summary>
/// Gets and sets the property User.
/// <para>
/// The user name.
/// </para>
/// </summary>
public User User
{
get { return this._user; }
set { this._user = value; }
}
// Check to see if User property is set
internal bool IsSetUser()
{
return this._user != null;
}
}
}
| 27.478723
| 108
| 0.581494
|
[
"Apache-2.0"
] |
Bio2hazard/aws-sdk-net
|
sdk/src/Services/QuickSight/Generated/Model/DescribeUserResponse.cs
| 2,583
|
C#
|
using System;
using System.ComponentModel.Composition;
using Microsoft.VisualStudio.Shell;
using SharperCryptoApiAnalysis.Interop.Services;
using SharperCryptoApiAnalysis.Shell.Commands;
using SharperCryptoApiAnalysis.Shell.Interop.Commands;
using SharperCryptoApiAnalysis.Shell.Interop.CryptoTaskGenerator;
using Task = System.Threading.Tasks.Task;
using WizardWindow = SharperCryptoApiAnalysis.Shell.Interop.Wizard.WizardWindow;
namespace SharperCryptoApiAnalysis.Vsix.Commands
{
[Export(typeof(IAddCryptoTaskCommand))]
internal class AddCryptoTaskCommand : VsCommand, IAddCryptoTaskCommand
{
public const int CommandId = PackageIds.AddCryptoAbstractionFile;
public static readonly Guid CommandSet = PackageGuids.SharperCryptoApiAnalysisCommandSet;
private ISharperCryptoAnalysisServiceProvider _serviceProvider;
private ICryptoCodeGenerationTaskProvider _cryptoCodeGenerationTaskProvider;
private ICryptoCodeGenerationTaskProvider CryptoCodeGenerationTaskProvider => _cryptoCodeGenerationTaskProvider ??
(_cryptoCodeGenerationTaskProvider = _serviceProvider.ExportProvider
.GetExportedValue<ICryptoCodeGenerationTaskProvider>());
[ImportingConstructor]
public AddCryptoTaskCommand(ISharperCryptoAnalysisServiceProvider serviceProvider) : base(CommandSet, CommandId)
{
_serviceProvider = serviceProvider;
}
public override async Task Execute()
{
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
var viewModel = new CryptoTaskWizardViewModel(CryptoCodeGenerationTaskProvider);
var w = new WizardWindow(viewModel);
w.ShowDialog();
if (!viewModel.Completed)
return;
var result = viewModel.Result as ICryptoCodeGenerationTask;
result?.TaskHandler.Execute(result.Model);
}
}
}
| 44.347826
| 125
| 0.720098
|
[
"MIT"
] |
AnakinSklavenwalker/SharperCryptoApiAnalysis
|
src/SharperCryptoApiAnalysis.Vsix/Commands/AddCryptoTaskCommand.cs
| 2,042
|
C#
|
// <copyright file="ProjectilePacket.cs" company="2Dudes">
// Copyright (c) 2018 2Dudes. All rights reserved.
// Licensed under the MIT license.
// See LICENSE file in the project root for full license information.
// </copyright>
using COMMO.Data.Contracts;
using COMMO.Server.Data;
using COMMO.Server.Data.Interfaces;
using COMMO.Server.Data.Models.Structs;
namespace COMMO.Communications.Packets.Outgoing
{
public class ProjectilePacket : PacketOutgoing
{
public override byte PacketType => (byte)GameOutgoingPacketType.CreatureMoved;
public Location FromLocation { get; set; }
public Location ToLocation { get; set; }
public ShotType ShootType { get; set; }
public override void Add(NetworkMessage message)
{
message.AddByte(PacketType);
message.AddLocation(FromLocation);
message.AddLocation(ToLocation);
message.AddByte((byte)ShootType);
}
public override void CleanUp()
{
// No references to clear.
}
}
}
| 27.487179
| 86
| 0.666045
|
[
"MIT"
] |
CoreOpenMMO/CoreOpenMMO
|
src/COMMO.Communications/Packets/Outgoing/ProjectilePacket.cs
| 1,072
|
C#
|
using System.Collections.Generic;
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using realmon.Utilities;
namespace realmon.UnitTests
{
[TestClass]
public class GetHeader
{
[TestMethod]
public void GetHeader_DefaultConfiguration_SuccessfulMatch()
{
Configuration.Configuration configuration = new Configuration.Configuration();
configuration.Columns = new List<string> { "type", "gen", "pause (ms)", "reason" };
string header = PrintUtilities.GetHeader(configuration);
header.Should().NotBeNullOrEmpty();
header.Should().BeEquivalentTo("GC# index | type | gen | pause (ms) | reason |");
}
}
}
| 34.727273
| 125
| 0.637435
|
[
"MIT"
] |
Maoni0/realmon
|
tests/GCRealTimeMon.UnitTests/PrintUtilities/GetHeader.cs
| 766
|
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace LukeVo.Games.Models
{
public class CardManager
{
public Stack<Card> Cards { get; private set; } = new Stack<Card>();
public void Add(int deck, bool shuffleAfterAdd)
{
for (int i = 0; i < deck; i++)
{
for (int num = 1; num < 14; num++)
{
for (int suit = 0; suit < 4; suit++)
{
this.Cards.Push(new Card(num, suit));
}
}
}
if (shuffleAfterAdd)
{
this.Shuffle();
}
}
public void Add(Card card)
{
this.Cards.Push(card);
}
public Card Deal()
{
if (this.Cards.Count > 0)
{
return this.Cards.Pop();
}
else
{
return null;
}
}
public void Shuffle()
{
var stack = this.Cards;
var cards = new List<Card>();
while (stack.Count > 0)
{
cards.Add(stack.Pop());
}
var random = new Random();
for (int i = 0; i < cards.Count; i++)
{
var index = random.Next(cards.Count);
var temp = cards[i];
cards[i] = cards[index];
cards[index] = temp;
}
foreach (var card in cards)
{
stack.Push(card);
}
}
public void Clear()
{
this.Cards.Clear();
}
}
public class Card
{
public Card(int num, int suit)
{
this.Num = num;
this.Suit = suit;
}
public int Num { get; set; }
public int Suit { get; set; }
}
}
| 21.042105
| 75
| 0.387194
|
[
"MIT"
] |
datvm/LukeVoWebsite
|
LukeVo.Games/Models/CardManager.cs
| 2,001
|
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.Linq;
using Microsoft.Azure;
using Microsoft.Azure.Commands.Sql.Location_Capabilities.Model;
using Microsoft.Azure.Commands.Sql.Services;
using Microsoft.Azure.Common.Authentication.Models;
namespace Microsoft.Azure.Commands.Sql.Location_Capabilities.Services
{
public class AzureSqlCapabilitiesAdapter
{
/// <summary>
/// The communicator for interacting with the service APIs
/// </summary>
private AzureSqlCapabilitiesCommunicator _communicator;
/// <summary>
/// Gets or sets the Azure profile
/// </summary>
public AzureContext Context { get; set; }
/// <summary>
/// Constructs a firewall rule adapter
/// </summary>
/// <param name="profile">The current azure profile</param>
/// <param name="subscription">The current azure subscription</param>
public AzureSqlCapabilitiesAdapter(AzureContext context)
{
Context = context;
_communicator = new AzureSqlCapabilitiesCommunicator(Context);
}
/// <summary>
/// Gets the capabilities for the specified location
/// </summary>
/// <param name="locationName">The name of the location for which to get the capabilities</param>
/// <returns></returns>
public LocationCapabilityModel GetLocationCapabilities(string locationName)
{
var resp = _communicator.Get(locationName, Util.GenerateTracingId());
return CreateLocationCapabilityModel(resp);
}
/// <summary>
/// Converts from an API object to a PowerShell object
/// </summary>
/// <param name="resp">The object to transform</param>
/// <returns>The converted location capability model</returns>
private LocationCapabilityModel CreateLocationCapabilityModel(Management.Sql.Models.LocationCapability resp)
{
LocationCapabilityModel model = new LocationCapabilityModel();
model.LocationName = resp.Name;
model.Status = resp.Status;
model.SupportedServerVersions = resp.SupportedServerVersions.Select(v => { return CreateSupportedVersionsModel(v); }).ToList();
return model;
}
/// <summary>
/// Converts from an API object to a PowerShell object
/// </summary>
/// <param name="v">The object to transform</param>
/// <returns>The converted server version capability model</returns>
private ServerVersionCapabilityModel CreateSupportedVersionsModel(Management.Sql.Models.ServerVersionCapability v)
{
ServerVersionCapabilityModel version = new ServerVersionCapabilityModel();
version.ServerVersionName = v.Name;
version.Status = v.Status;
version.SupportedEditions = v.SupportedEditions.Select(e => { return CreateSupportedEditionModel(e); }).ToList();
return version;
}
/// <summary>
/// Converts from an API object to a PowerShell object
/// </summary>
/// <param name="e">The object to transform</param>
/// <returns>The converted database edition capability model</returns>
private EditionCapabilityModel CreateSupportedEditionModel(Management.Sql.Models.EditionCapability e)
{
EditionCapabilityModel edition = new EditionCapabilityModel();
edition.EditionName = e.Name;
edition.Status = e.Status;
edition.SupportedServiceObjectives = e.SupportedServiceObjectives.Select(slo => { return CreateSupportedSLOModel(slo); }).ToList();
return edition;
}
/// <summary>
/// Converts from an API object to a PowerShell object
/// </summary>
/// <param name="s">The object to transform</param>
/// <returns>The converted edition Service Level Objective capability model</returns>
private ServiceObjectiveCapabilityModel CreateSupportedSLOModel(Management.Sql.Models.ServiceObjectiveCapability s)
{
ServiceObjectiveCapabilityModel slo = new ServiceObjectiveCapabilityModel();
slo.Id = s.Id;
slo.ServiceObjectiveName = s.Name;
slo.Status = s.Status;
slo.SupportedMaxSizes = s.SupportedMaxSizes.Select(m => { return CreateSupportedMaxSizeModel(m); }).ToList();
return slo;
}
/// <summary>
/// Converts from an API object to a PowerShell object
/// </summary>
/// <param name="e">The object to transform</param>
/// <returns>The converted database max size capability model</returns>
private MaxSizeCapabilityModel CreateSupportedMaxSizeModel(Management.Sql.Models.MaxSizeCapability m)
{
MaxSizeCapabilityModel maxSize = new MaxSizeCapabilityModel();
maxSize.Limit = m.Limit;
maxSize.Status = m.Status;
maxSize.Unit = m.Unit;
return maxSize;
}
}
}
| 44.06015
| 144
| 0.632594
|
[
"MIT"
] |
KinaMarie/azure-powershell
|
src/ResourceManager/Sql/Commands.Sql/Location Capabilities/Services/AzureSqlCapabilitiesAdapter.cs
| 5,730
|
C#
|
#region Copyright
/*Copyright (C) 2015 Konstantin Udilovich
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Kodestruct.Concrete.ACI
{
public class TCIterationBound
{
public double MaxStrain { get; set; }
public double MinStrain { get; set; }
}
}
| 27.9375
| 75
| 0.731544
|
[
"Apache-2.0"
] |
Kodestruct/Kodestruct.Design
|
Kodestruct.Concrete/ACI/Entities/Common/TCIterationBound.cs
| 894
|
C#
|
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Aws.Ec2
{
public static class GetVpnGateway
{
/// <summary>
/// The VPN Gateway data source provides details about
/// a specific VPN gateway.
///
/// {{% examples %}}
/// {{% /examples %}}
/// </summary>
public static Task<GetVpnGatewayResult> InvokeAsync(GetVpnGatewayArgs? args = null, InvokeOptions? options = null)
=> Pulumi.Deployment.Instance.InvokeAsync<GetVpnGatewayResult>("aws:ec2/getVpnGateway:getVpnGateway", args ?? new GetVpnGatewayArgs(), options.WithVersion());
}
public sealed class GetVpnGatewayArgs : Pulumi.InvokeArgs
{
/// <summary>
/// The Autonomous System Number (ASN) for the Amazon side of the specific VPN Gateway to retrieve.
/// </summary>
[Input("amazonSideAsn")]
public string? AmazonSideAsn { get; set; }
/// <summary>
/// The ID of a VPC attached to the specific VPN Gateway to retrieve.
/// </summary>
[Input("attachedVpcId")]
public string? AttachedVpcId { get; set; }
/// <summary>
/// The Availability Zone of the specific VPN Gateway to retrieve.
/// </summary>
[Input("availabilityZone")]
public string? AvailabilityZone { get; set; }
[Input("filters")]
private List<Inputs.GetVpnGatewayFilterArgs>? _filters;
/// <summary>
/// Custom filter block as described below.
/// </summary>
public List<Inputs.GetVpnGatewayFilterArgs> Filters
{
get => _filters ?? (_filters = new List<Inputs.GetVpnGatewayFilterArgs>());
set => _filters = value;
}
/// <summary>
/// The ID of the specific VPN Gateway to retrieve.
/// </summary>
[Input("id")]
public string? Id { get; set; }
/// <summary>
/// The state of the specific VPN Gateway to retrieve.
/// </summary>
[Input("state")]
public string? State { get; set; }
[Input("tags")]
private Dictionary<string, object>? _tags;
/// <summary>
/// A mapping of tags, each pair of which must exactly match
/// a pair on the desired VPN Gateway.
/// </summary>
public Dictionary<string, object> Tags
{
get => _tags ?? (_tags = new Dictionary<string, object>());
set => _tags = value;
}
public GetVpnGatewayArgs()
{
}
}
[OutputType]
public sealed class GetVpnGatewayResult
{
public readonly string AmazonSideAsn;
public readonly string AttachedVpcId;
public readonly string AvailabilityZone;
public readonly ImmutableArray<Outputs.GetVpnGatewayFilterResult> Filters;
public readonly string Id;
public readonly string State;
public readonly ImmutableDictionary<string, object> Tags;
[OutputConstructor]
private GetVpnGatewayResult(
string amazonSideAsn,
string attachedVpcId,
string availabilityZone,
ImmutableArray<Outputs.GetVpnGatewayFilterResult> filters,
string id,
string state,
ImmutableDictionary<string, object> tags)
{
AmazonSideAsn = amazonSideAsn;
AttachedVpcId = attachedVpcId;
AvailabilityZone = availabilityZone;
Filters = filters;
Id = id;
State = state;
Tags = tags;
}
}
}
| 30.880952
| 170
| 0.59008
|
[
"ECL-2.0",
"Apache-2.0"
] |
johnktims/pulumi-aws
|
sdk/dotnet/Ec2/GetVpnGateway.cs
| 3,891
|
C#
|
using rover.Interfaces;
using System;
using System.Collections.Generic;
using System.Text;
namespace rover.Classes
{
class Movement : IMovement
{
public void Process(string commands,Common common)
{
for (int idx = 0; idx < commands.Length; idx++)
{
Process(commands[idx], common);
}
}
private void Process(char command, Common common)
{
if (command.Equals('L'))
{
TurnLeft(common);
}
else if (command.Equals('R'))
{
TurnRight(common);
}
else if (command.Equals('M'))
{
Move(common);
}
else
{
throw new Exception("Speak in Mars language, please!");
}
}
public void TurnLeft( Common common)
{
common.facing = (common.facing - 1) < Common.N ? Common.W : common.facing - 1;
}
public void TurnRight( Common common)
{
common.facing = (common.facing + 1) > Common.W ? Common.N : common.facing + 1;
}
private void Move(Common common)
{
if (common.facing == Common.N)
{
common.y++;
}
else if (common.facing == Common.E)
{
common.x++;
}
else if (common.facing == Common.S)
{
common.y--;
}
else if (common.facing == Common.W)
{
common.x--;
}
}
}
}
| 24.850746
| 90
| 0.428228
|
[
"MIT"
] |
PersistentGaneshGadekar/rover
|
rover/Classes/Movement.cs
| 1,667
|
C#
|
//----------------------------------------------
// Realistic Car Controller
//
// Copyright © 2014 - 2020 BoneCracker Games
// http://www.bonecrackergames.com
// Buğra Özdoğanlar
//
//----------------------------------------------
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RCC_DetachablePart : MonoBehaviour{
public Transform COM; // Center of mass.
private Rigidbody rigid; // Rigidbody.
public bool lockAtStart = true; // Lock all motions of Configurable Joint at start.
public float strength = 100f; // Strength of the part.
private bool broken = false; // Is this part broken?
public bool isBreakable = true; // Can it break at certain damage?
public bool isDetachable = true; // Can it detach from the vehicle at certain damage?
public int loosePoint = 35; // Part will be broken at this point.
public int detachPoint = 0; // Part will be detached at this point.
public Vector3 addTorqueAfterLoose = Vector3.zero; // Adds angular velocity related to speed after the brake point reached.
[System.Serializable]
private class DetachableJoint{
[HideInInspector]
public ConfigurableJoint joint;
internal ConfigurableJointMotion jointMotionAngularX;
internal ConfigurableJointMotion jointMotionAngularY;
internal ConfigurableJointMotion jointMotionAngularZ;
internal ConfigurableJointMotion jointMotionX;
internal ConfigurableJointMotion jointMotionY;
internal ConfigurableJointMotion jointMotionZ;
}
private DetachableJoint detachableJoint = new DetachableJoint();
void Start(){
rigid = GetComponent<Rigidbody> (); // Getting Rigidbody of the part.
ConfigurableJoint joint = gameObject.GetComponent<ConfigurableJoint>(); // Getting Configurable Joint of the part.
// Setting center of mass if selected.
if (COM)
rigid.centerOfMass = transform.InverseTransformPoint(COM.transform.position);
// If configurable joint found, set it. Otherwise disable the script.
if (joint){
detachableJoint.joint = joint;
}else{
Debug.LogWarning ("Configurable Joint not found for " + gameObject.name + "!");
enabled = false;
return;
}
// Locks all motions of Configurable Joint at start.
if (lockAtStart)
StartCoroutine(LockParts ());
}
/// <summary>
/// Locks the parts.
/// </summary>
private IEnumerator LockParts(){
yield return new WaitForFixedUpdate ();
// Getting default settings of the part.
detachableJoint.jointMotionAngularX = detachableJoint.joint.angularXMotion;
detachableJoint.jointMotionAngularY = detachableJoint.joint.angularYMotion;
detachableJoint.jointMotionAngularZ = detachableJoint.joint.angularZMotion;
detachableJoint.jointMotionX = detachableJoint.joint.xMotion;
detachableJoint.jointMotionY = detachableJoint.joint.yMotion;
detachableJoint.jointMotionZ = detachableJoint.joint.zMotion;
// Locking the part.
detachableJoint.joint.angularXMotion = ConfigurableJointMotion.Locked;
detachableJoint.joint.angularYMotion = ConfigurableJointMotion.Locked;
detachableJoint.joint.angularZMotion = ConfigurableJointMotion.Locked;
detachableJoint.joint.xMotion = ConfigurableJointMotion.Locked;
detachableJoint.joint.yMotion = ConfigurableJointMotion.Locked;
detachableJoint.joint.zMotion = ConfigurableJointMotion.Locked;
}
void Update(){
// If part is broken, return.
if (broken)
return;
// If part is weak and loosen, apply angular velocity related to speed.
if (addTorqueAfterLoose != Vector3.zero && strength <= loosePoint) {
float speed = transform.InverseTransformDirection (rigid.velocity).z;
rigid.AddRelativeTorque (new Vector3(addTorqueAfterLoose.x * speed, addTorqueAfterLoose.y * speed, addTorqueAfterLoose.z * speed));
}
}
public void OnCollision (Collision collision){
// If part is broken, return.
if (broken)
return;
Vector3 colRelVel = collision.relativeVelocity;
colRelVel *= 1f - Mathf.Abs (Vector3.Dot (transform.up, collision.contacts [0].normal));
float cos = Mathf.Abs (Vector3.Dot (collision.contacts [0].normal, colRelVel.normalized));
foreach (ContactPoint contact in collision.contacts){
Vector3 point = transform.InverseTransformPoint(contact.point);
if (point.magnitude < 2f) {
strength -= (2f - (point.magnitude)) * cos * 10f;
strength = Mathf.Clamp (strength, 0f, Mathf.Infinity);
}
}
DamageParts (); // Damage parts.
}
/// <summary>
/// Damages the parts.
/// </summary>
private void DamageParts(){
// If part is broken, return.
if (broken)
return;
// Unlocking the parts and set their joint configuration to default.
if (strength <= detachPoint) {
if (detachableJoint.joint) {
broken = true;
Destroy (detachableJoint.joint);
transform.SetParent (null);
Destroy(gameObject, 3f);
}
}else if (strength <= loosePoint) {
if (detachableJoint.joint) {
detachableJoint.joint.angularXMotion = detachableJoint.jointMotionAngularX;
detachableJoint.joint.angularYMotion = detachableJoint.jointMotionAngularY;
detachableJoint.joint.angularZMotion = detachableJoint.jointMotionAngularZ;
detachableJoint.joint.xMotion = detachableJoint.jointMotionX;
detachableJoint.joint.yMotion = detachableJoint.jointMotionY;
detachableJoint.joint.zMotion = detachableJoint.jointMotionZ;
}
}
}
}
| 28.643617
| 134
| 0.731662
|
[
"MIT"
] |
MassiveAkib/collab-AM
|
Assets/RealisticCarControllerV3/Scripts/RCC_DetachablePart.cs
| 5,391
|
C#
|
namespace P07_InfernoInfinity.Models.Weapons
{
using Enums;
public class Sword : Weapon
{
private const int BaseMinDamage = 4;
private const int BaseMaxDamage = 6;
private const int Sockets = 3;
public Sword(WeaponRarity weaponRarity, string name)
: base(weaponRarity, name, BaseMinDamage, BaseMaxDamage, Sockets)
{
}
}
}
| 23.588235
| 77
| 0.628429
|
[
"MIT"
] |
MertYumer/C-Fundamentals---January-2019
|
C# OOP - February 2019/07. Reflection and Attributes - Exercises/P07-InfernoInfinity/Models/Weapons/Sword.cs
| 403
|
C#
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Hec.Ensemble
{
[DebuggerDisplay("{Name}")]
public class Watershed
{
public Watershed(string name)
{
this.Name = name;
Locations = new List<Location>(10);
}
public string Name { get; set; }
public List<Location> Locations { get; set; }
public Forecast AddForecast(string locName, DateTime issueDate, float[,] ensemble, DateTime[] timeStamps)
{
Location loc = GetOrCreateLocation(locName);
var rval = loc.AddForecast(issueDate, ensemble, timeStamps);
return rval;
}
private Location GetOrCreateLocation(string locName)
{
int idx = Locations.FindIndex(x => x.Name.Equals(locName));
Location loc = null;
if (idx >= 0)
loc = Locations[idx];
else
{
loc = new Location(locName, this);
Locations.Add(loc);
}
return loc;
}
public Watershed CloneSubset(int takeCount)
{
int count = 0;
var retn = new Watershed(this.Name);
foreach (Location loc in this.Locations)
{
foreach (Forecast f in loc.Forecasts)
{
retn.AddForecast(f.Location.Name, f.IssueDate, f.Ensemble,f.TimeStamps);
count++;
if( count >= takeCount)
break;
}
}
return retn;
}
}
}
| 22.060606
| 109
| 0.60783
|
[
"MIT"
] |
HydrologicEngineeringCenter/DSSConversions
|
HEFS_To_DSS/Hec.Ensemble/Watershed.cs
| 1,458
|
C#
|
/*
Copyright (c) Shubham Saudolla
https://github.com/shubham-saudolla
*/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Audio;
using System;
public class AudioManager : MonoBehaviour
{
public Sound[] sounds;
public static AudioManager instance;
private void Awake()
{
DontDestroyOnLoad(gameObject);
if (instance == null)
instance = this;
else if (instance != this)
Destroy(gameObject);
}
private void Start()
{
foreach (Sound s in sounds)
{
s.source = gameObject.AddComponent<AudioSource>();
s.source.clip = s.clip;
s.source.volume = s.volume;
s.source.loop = s.loop;
}
}
public void Play(string name)
{
Sound s = Array.Find(sounds, sounds => sounds.name == name);
if (s == null)
{
Debug.LogError("Sound " + name + " not found");
return;
}
s.source.Play();
}
}
| 20.173077
| 68
| 0.56244
|
[
"MIT"
] |
shubham-saudolla/ZigZag
|
ZigZag/Assets/Scripts/AudioManager.cs
| 1,051
|
C#
|
using Abp.Domain.Entities.Auditing;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text;
namespace reactjs.Models
{
public class Book: FullAuditedEntity
{
[Required]
[Display(Name ="Display Name")]
[StringLength(64, ErrorMessage ="Maximum Length is 64")]
public string DispalyName { get; set; }
public Nullable<int> TotalPageNumber { get; set; }
[ForeignKey("Author")]
public int AuthorId { get; set; }
[ForeignKey("Category")]
public int CategoryId { get; set; }
public virtual Author Author { get; set; }
public virtual Category Category { get; set; }
}
}
| 30.84
| 64
| 0.66537
|
[
"MIT"
] |
tranbinhvn/abpReact
|
aspnet-core/src/aspReact.Core/Models/Book.cs
| 773
|
C#
|
using System;
namespace Godot
{
public static partial class ResourceLoader
{
/// <summary>
/// Loads a resource at the given <paramref name="path"/>, caching the result
/// for further access.
/// The registered <see cref="ResourceFormatLoader"/> instances are queried sequentially
/// to find the first one which can handle the file's extension, and then attempt
/// loading. If loading fails, the remaining ResourceFormatLoaders are also attempted.
/// An optional <paramref name="typeHint"/> can be used to further specify the
/// <see cref="Resource"/> type that should be handled by the <see cref="ResourceFormatLoader"/>.
/// Anything that inherits from <see cref="Resource"/> can be used as a type hint,
/// for example <see cref="Image"/>.
/// If <paramref name="noCache"/> is <see langword="true"/>, the resource cache will be bypassed and
/// the resource will be loaded anew. Otherwise, the cached resource will be returned if it exists.
/// Returns an empty resource if no <see cref="ResourceFormatLoader"/> could handle the file.
/// </summary>
/// <exception cref="InvalidCastException">
/// Thrown when the given the loaded resource can't be casted to the given type <typeparamref name="T"/>.
/// </exception>
/// <typeparam name="T">The type to cast to. Should be a descendant of <see cref="Resource"/>.</typeparam>
public static T Load<T>(string path, string typeHint = null, bool noCache = false) where T : class
{
return (T)(object)Load(path, typeHint, noCache);
}
}
}
| 54.225806
| 114
| 0.644259
|
[
"MIT",
"Apache-2.0",
"Unlicense"
] |
filipworksdev/goblin-test
|
modules/mono/glue/GodotSharp/GodotSharp/Core/Extensions/ResourceLoaderExtensions.cs
| 1,681
|
C#
|
using System;
using System.Linq;
using Abp.AspNetCore.EmbeddedResources;
using Abp.AspNetCore.Localization;
using Abp.Dependency;
using Abp.Localization;
using Castle.LoggingFacility.MsLogging;
using JetBrains.Annotations;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Localization;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System.Globalization;
using Abp.AspNetCore.Security;
namespace Abp.AspNetCore
{
public static class AbpApplicationBuilderExtensions
{
public static void UseAbp(this IApplicationBuilder app)
{
app.UseAbp(null);
}
public static void UseAbp([NotNull] this IApplicationBuilder app, Action<AbpApplicationBuilderOptions> optionsAction)
{
Check.NotNull(app, nameof(app));
var options = new AbpApplicationBuilderOptions();
optionsAction?.Invoke(options);
if (options.UseCastleLoggerFactory)
{
app.UseCastleLoggerFactory();
}
InitializeAbp(app);
if (options.UseAbpRequestLocalization)
{
//TODO: This should be added later than authorization middleware!
app.UseAbpRequestLocalization();
}
if (options.UseSecurityHeaders)
{
app.UseAbpSecurityHeaders();
}
}
public static void UseEmbeddedFiles(this IApplicationBuilder app)
{
app.UseStaticFiles(
new StaticFileOptions
{
FileProvider = new EmbeddedResourceFileProvider(
app.ApplicationServices.GetRequiredService<IIocResolver>()
)
}
);
}
private static void InitializeAbp(IApplicationBuilder app)
{
var abpBootstrapper = app.ApplicationServices.GetRequiredService<AbpBootstrapper>();
abpBootstrapper.Initialize();
}
public static void UseCastleLoggerFactory(this IApplicationBuilder app)
{
var castleLoggerFactory = app.ApplicationServices.GetService<Castle.Core.Logging.ILoggerFactory>();
if (castleLoggerFactory == null)
{
return;
}
app.ApplicationServices
.GetRequiredService<ILoggerFactory>()
.AddCastleLogger(castleLoggerFactory);
}
public static void UseAbpRequestLocalization(this IApplicationBuilder app, Action<RequestLocalizationOptions> optionsAction = null)
{
var iocResolver = app.ApplicationServices.GetRequiredService<IIocResolver>();
using (var languageManager = iocResolver.ResolveAsDisposable<ILanguageManager>())
{
var supportedCultures = languageManager.Object
.GetLanguages()
.Select(l => CultureInfo.GetCultureInfo(l.Name))
.ToArray();
var options = new RequestLocalizationOptions
{
SupportedCultures = supportedCultures,
SupportedUICultures = supportedCultures
};
var userProvider = new AbpUserRequestCultureProvider();
//0: QueryStringRequestCultureProvider
options.RequestCultureProviders.Insert(1, userProvider);
options.RequestCultureProviders.Insert(2, new AbpLocalizationHeaderRequestCultureProvider());
//3: CookieRequestCultureProvider
options.RequestCultureProviders.Insert(4, new AbpDefaultRequestCultureProvider());
//5: AcceptLanguageHeaderRequestCultureProvider
optionsAction?.Invoke(options);
userProvider.CookieProvider = options.RequestCultureProviders.OfType<CookieRequestCultureProvider>().FirstOrDefault();
userProvider.HeaderProvider = options.RequestCultureProviders.OfType<AbpLocalizationHeaderRequestCultureProvider>().FirstOrDefault();
app.UseRequestLocalization(options);
}
}
public static void UseAbpSecurityHeaders(this IApplicationBuilder app)
{
app.UseMiddleware<AbpSecurityHeadersMiddleware>();
}
}
}
| 35.909836
| 149
| 0.628167
|
[
"MIT"
] |
NandipMakwana/aspnetboilerplate
|
src/Abp.AspNetCore/AspNetCore/AbpApplicationBuilderExtensions.cs
| 4,383
|
C#
|
//******************************************************************
//
// Copyright (c) Microsoft Corporation. All rights reserved.
// This code is licensed under the Visual Studio SDK license terms.
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//******************************************************************
// Guids.cs
// MUST match guids.h
using System;
namespace PhotoStudio.AboutBoxPackage
{
static class GuidList
{
public const string guidAboutBoxPackagePkgString = "c3999640-0406-40cf-ba15-541ff8cf0c08";
public const string guidAboutBoxPackageCmdSetString = "15fdc884-a51c-4a8a-8003-8eb5c2f0d4fc";
public static readonly Guid guidAboutBoxPackageCmdSet = new Guid(guidAboutBoxPackageCmdSetString);
};
}
| 39.25
| 107
| 0.626327
|
[
"Apache-2.0"
] |
LiveMirror/Visual-Studio-2010-SDK-Samples
|
Sample setup program for shell applications/C# and C++/C#,C++/PhotoStudio/PhotoStudio.AboutBoxPackage/Guids.cs
| 944
|
C#
|
using System;
namespace Esfa.Vacancy.Api.Types
{
/// <summary>
/// An apprenticeship vacancy
/// </summary>
public class ApprenticeshipVacancy
{
/// <summary>
/// Reference number.
/// </summary>
public long VacancyReference { get; set; }
/// <summary>
/// Vacancy Title.
/// </summary>
public string Title { get; set; }
/// <summary>
/// The short description of the vacancy.
/// </summary>
public string ShortDescription { get; set; }
/// <summary>
/// The long description of the vacancy.
/// </summary>
public string Description { get; set; }
/// <summary>
/// Wage unit.
/// </summary>
public WageUnit WageUnit { get; set; }
/// <summary>
/// Working week.
/// </summary>
public string WorkingWeek { get; set; }
/// <summary>
/// Wage text.
/// </summary>
public string WageText { get; set; }
/// <summary>
/// Additional information with regards to wages
/// </summary>
public string WageAdditionalInformation { get; set; }
/// <summary>
/// Hours per week.
/// </summary>
public decimal? HoursPerWeek { get; set; }
/// <summary>
/// Expected duration.
/// </summary>
public string ExpectedDuration { get; set; }
/// <summary>
/// Expected start date.
/// </summary>
public DateTime? ExpectedStartDate { get; set; }
/// <summary>
/// Date posted.
/// </summary>
public DateTime PostedDate { get; set; }
/// <summary>
/// Application closing date.
/// </summary>
public DateTime? ApplicationClosingDate { get; set; }
/// <summary>
/// Number of positions.
/// </summary>
public int NumberOfPositions { get; set; }
/// <summary>
/// Training Type
/// </summary>
public TrainingType TrainingType { get; set; }
/// <summary>
/// Training title.
/// </summary>
public string TrainingTitle { get; set; }
/// <summary>
/// Training identifier
/// </summary>
public string TrainingCode { get; set; }
/// <summary>
/// The name of the employer.
/// </summary>
public string EmployerName { get; set; }
/// <summary>
/// Employer's description.
/// </summary>
public string EmployerDescription { get; set; }
/// <summary>
/// Employers website.
/// </summary>
public string EmployerWebsite { get; set; }
/// <summary>
/// Training to be provided.
/// </summary>
public string TrainingToBeProvided { get; set; }
/// <summary>
/// Qualifications required.
/// </summary>
public string QualificationsRequired { get; set; }
/// <summary>
/// Skills required.
/// </summary>
public string SkillsRequired { get; set; }
/// <summary>
/// Personal qualities.
/// </summary>
public string PersonalQualities { get; set; }
/// <summary>
/// Future prospects.
/// </summary>
public string FutureProspects { get; set; }
/// <summary>
/// Things to consider.
/// </summary>
public string ThingsToConsider { get; set; }
/// <summary>
/// Is this vacancy available nationwide.
/// </summary>
public bool IsNationwide { get; set; }
/// <summary>
/// Supplementary question1.
/// </summary>
public string SupplementaryQuestion1 { get; set; }
/// <summary>
/// Supplementary question2.
/// </summary>
public string SupplementaryQuestion2 { get; set; }
/// <summary>
/// Vacancy URL.
/// </summary>
public string VacancyUrl { get; set; }
/// <summary>
/// Contains the address of the Vacancy
/// </summary>
public GeoCodedAddress Location { get; set; }
/// <summary>
/// Name of the contact person
/// </summary>
public string ContactName { get; set; }
/// <summary>
/// Email of the contact person
/// </summary>
public string ContactEmail { get; set; }
/// <summary>
/// Phone number of the contact person
/// </summary>
public string ContactNumber { get; set; }
/// <summary>
/// The training provider's trading name
/// </summary>
public string TrainingProviderName { get; set; }
/// <summary>
/// The training provider's UKPRN
/// </summary>
public string TrainingProviderUkprn { get; set; }
/// <summary>
/// The training provider site
/// </summary>
public string TrainingProviderSite { get; set; }
/// <summary>
/// Is employer disability confident.
/// </summary>
public bool IsEmployerDisabilityConfident { get; set; }
/// <summary>
/// Vacancy apprenticeship level.
/// </summary>
public string ApprenticeshipLevel { get; set; }
/// <summary>
/// Instructions on how to apply for the vacancy
/// </summary>
public string ApplicationInstructions { get; set; }
/// <summary>
/// The web URL for applying for the vacancy
/// </summary>
public string ApplicationUrl { get; set; }
}
}
| 26.592593
| 63
| 0.507834
|
[
"MIT"
] |
SkillsFundingAgency/das-vacancyservices-api
|
src/Esfa.Vacancy.Api.Types/ApprenticeshipVacancy.cs
| 5,746
|
C#
|
using System;
namespace Clipify.Playlist.Domain
{
public class Class1
{
}
}
| 10
| 33
| 0.644444
|
[
"MIT"
] |
Mikyan0207/clipify-cloud
|
source/Clipify.Playlist.Domain/Class1.cs
| 92
|
C#
|
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the sesv2-2019-09-27.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.SimpleEmailV2.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.SimpleEmailV2.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for ReviewDetails Object
/// </summary>
public class ReviewDetailsUnmarshaller : IUnmarshaller<ReviewDetails, XmlUnmarshallerContext>, IUnmarshaller<ReviewDetails, JsonUnmarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
ReviewDetails IUnmarshaller<ReviewDetails, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context)
{
throw new NotImplementedException();
}
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public ReviewDetails Unmarshall(JsonUnmarshallerContext context)
{
context.Read();
if (context.CurrentTokenType == JsonToken.Null)
return null;
ReviewDetails unmarshalledObject = new ReviewDetails();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("CaseId", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.CaseId = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("Status", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.Status = unmarshaller.Unmarshall(context);
continue;
}
}
return unmarshalledObject;
}
private static ReviewDetailsUnmarshaller _instance = new ReviewDetailsUnmarshaller();
/// <summary>
/// Gets the singleton.
/// </summary>
public static ReviewDetailsUnmarshaller Instance
{
get
{
return _instance;
}
}
}
}
| 34.142857
| 152
| 0.627017
|
[
"Apache-2.0"
] |
ChristopherButtars/aws-sdk-net
|
sdk/src/Services/SimpleEmailV2/Generated/Model/Internal/MarshallTransformations/ReviewDetailsUnmarshaller.cs
| 3,346
|
C#
|
namespace Danmaku2Lib
{
public enum Key
{
A, B, C, D, E, F, G, H, I, J, K, L, M,
N, O, P, Q, R, S, T, U, V, W, X, Y, Z,
Zero, One, Two, Three, Four, Five, Six, Seven, Eight, Nine,
UpArrow, DownArrow, LeftArrow, RightArrow,
Delete, Backspace, Enter, Shift, Space,
Esc
}
public interface IKeyboard
{
bool IsPressed(Key key);
}
}
| 19.368421
| 62
| 0.570652
|
[
"MIT"
] |
dtsudo/DT-Danmaku-2
|
Source code/Danmaku2Lib/IKeyboard.cs
| 370
|
C#
|
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using XData.Data.Schema;
using XData.Data.Resources;
using System.Diagnostics;
using System.ComponentModel;
namespace XData.Data.Objects
{
public abstract partial class Database
{
// is a Element
protected abstract class ExecuteUnit
{
protected readonly Database Database;
protected readonly XElement Element;
protected readonly XElement Schema;
public ExecuteUnit(Database database, XElement element, XElement schema)
{
Database = database;
Element = element;
Schema = schema;
}
public abstract void ExecuteNonQuery();
private DbCommand _command = null;
protected DbCommand GetCommand()
{
if (_command == null)
{
_command = Database.Connection.CreateCommand();
if (Database.Transaction != null)
{
_command.Transaction = Database.Transaction;
}
}
return _command;
}
protected Relationship GetChildrenToParentRelationship(string childrenName, string parentName)
{
XElement childElementSchema = Schema.GetElementSchemaBySetName(childrenName);
var childRelationship = Schema.CreateRelationship(childElementSchema.Name.LocalName, parentName);
if (childRelationship == null || childRelationship is OneToManyRelationship)
{
throw new SchemaException(string.Format(Messages.Validation_No_Available_Relationship, childrenName, parentName),
Schema);
}
return childRelationship;
}
// CreateUnit, UpdateUnit
// <User>
// <Pserson> // inversion
// <Id>123</Id>
// ...
// </Person>
// </User>
protected void SetFromInternalParents(string xPath, XElement node)
{
foreach (XElement parent in node.Elements().Where(p => p.HasElements))
{
if (!Schema.IsElement(parent)) continue;
SetFromInternalParent(xPath, node, parent);
}
}
private void SetFromInternalParent(string xPath, XElement node, XElement parent)
{
Relationship relationship = Schema.CreateToOneRelationship(node.Name.LocalName, parent.Name.LocalName);
if (relationship == null) return;
if (relationship is ManyToOneRelationship || relationship is OneToOneRelationship)
{
SimpleRelationship simpleRelationship = relationship as SimpleRelationship;
for (int i = 0; i < simpleRelationship.FieldNames.Length; i++)
{
string name = simpleRelationship.FieldNames[i];
string value = parent.Element(simpleRelationship.RelatedFieldNames[i]).Value;
if (node.Element(name) == null || string.IsNullOrWhiteSpace(node.Element(name).Value))
{
node.SetElementValue(name, value);
}
else
{
Debug.Assert(node.Element(name).Value == value);
}
}
}
}
// Delete, Update without Original
protected IEnumerable<XElement> GetChildrenFromDatabase(XElement parent, ManyToManyRelationship childrenToParentRelationship)
{
var manyToOneRelationship = childrenToParentRelationship.ManyToOneRelationship;
XElement dbChild = new XElement(manyToOneRelationship.ElementName);
for (int i = 0; i < manyToOneRelationship.FieldNames.Length; i++)
{
dbChild.SetElementValue(manyToOneRelationship.FieldNames[i],
parent.Element(manyToOneRelationship.RelatedFieldNames[i]).Value);
}
return Database.GetDatabaseElements(dbChild, Schema);
}
// Delete, Update without Original
protected IEnumerable<XElement> GetChildrenFromDatabase(XElement parent, SimpleRelationship childrenToParentRelationship)
{
Debug.Assert(childrenToParentRelationship is ManyToOneRelationship || childrenToParentRelationship is OneToOneRelationship);
XElement dbChild = new XElement(childrenToParentRelationship.ElementName);
for (int i = 0; i < childrenToParentRelationship.FieldNames.Length; i++)
{
dbChild.SetElementValue(childrenToParentRelationship.FieldNames[i],
parent.Element(childrenToParentRelationship.RelatedFieldNames[i]).Value);
}
return Database.GetDatabaseElements(dbChild, Schema);
}
// Delete, Update without Original
protected XElement GetDeleteOrUpdateWhereNode(XElement node, XElement keySchema, XElement timestampSchema, XElement concurrencyCheckSchema)
{
XElement whereNode = keySchema.ExtractKey(node);
if (timestampSchema != null)
{
XElement timestamp = timestampSchema.ExtractTimestamp(node);
whereNode.SetElementValue(timestamp.Name, timestamp.Value);
}
if (concurrencyCheckSchema != null)
{
XElement checksElement = concurrencyCheckSchema.ExtractConcurrencyChecks(node);
whereNode.Add(checksElement.Elements());
}
return whereNode;
}
// Delete, Update without Original
protected XElement FindDbChild(IEnumerable<XElement> dbChildren, XElement child,
XElement childKeySchema, XElement childTimestampSchema, XElement childConcurrencyCheckSchema, string xPath)
{
//
XElement timestamp = null;
if (childTimestampSchema != null)
{
timestamp = childTimestampSchema.ExtractTimestamp(child);
if (timestamp == null)
throw new ConcurrencyCheckException(child, null, xPath, Element, Schema);
}
//
XElement concurrencyChecks = null;
if (childConcurrencyCheckSchema != null)
{
concurrencyChecks = childConcurrencyCheckSchema.ExtractConcurrencyChecks(child);
if (concurrencyChecks == null)
throw new ConcurrencyCheckException(child, null, xPath, Element, Schema);
}
//
XElement value = childKeySchema.ExtractKey(child);
IEnumerable<XElement> result = dbChildren.Filter(value);
if (result.Count() > 1) throw new UnexpectedException("Duplicated.");
XElement dbChild = (result.Count() == 0) ? null : result.First();
if (dbChild != null)
{
//
if (childTimestampSchema != null)
{
if (childTimestampSchema.ExtractTimestamp(dbChild) != timestamp)
throw new ConcurrencyCheckException(child, null, xPath, Element, Schema);
}
//
if (childConcurrencyCheckSchema != null)
{
if (!XNode.DeepEquals(childConcurrencyCheckSchema.ExtractConcurrencyChecks(dbChild), concurrencyChecks))
throw new ConcurrencyCheckException(child, null, xPath, Element, Schema);
}
}
return dbChild;
}
// Delete, Update without Original
protected XElement GetSetNullSchema(XElement childElementSchema, SimpleRelationship childrenToParentRelationship)
{
Debug.Assert(childrenToParentRelationship is ManyToOneRelationship || childrenToParentRelationship is OneToOneRelationship);
XElement nullSchema = new XElement(childElementSchema.Name);
for (int i = 0; i < childrenToParentRelationship.FieldNames.Length; i++)
{
XElement fieldSchema = childElementSchema.Element(childrenToParentRelationship.FieldNames[i]);
if (fieldSchema.Element("Required") == null)
{
nullSchema.Add(new XElement(fieldSchema.Name));
continue;
}
nullSchema = null;
break;
}
return nullSchema;
}
// Delete, Update without Original
// ManyToMany
protected XElement GetSetNullSchema(XElement dbChildElementSchema, OneToManyRelationship relationship)
{
XElement nullSchema = new XElement(dbChildElementSchema.Name);
for (int i = 0; i < relationship.FieldNames.Length; i++)
{
XElement fieldSchema = dbChildElementSchema.Element(relationship.RelatedFieldNames[i]);
if (fieldSchema.Attribute("AllowDBNull").Value == "True" && fieldSchema.Element("Required") == null)
{
nullSchema.Add(new XElement(fieldSchema.Name));
}
else
{
nullSchema = new XElement(dbChildElementSchema.Name);
break;
}
}
return nullSchema.HasElements ? nullSchema : null;
}
// Delete, Update without Original
// ManyToMany
// UserRoles, Role
protected XElement FindDbChild(IEnumerable<XElement> dbChildren, XElement child, OneToManyRelationship relationship)
{
XElement value = new XElement(relationship.RelatedElementName);
for (int i = 0; i < relationship.RelatedFieldNames.Length; i++)
{
value.SetElementValue(relationship.RelatedFieldNames[i],
child.Element(relationship.FieldNames[i]).Value);
}
IEnumerable<XElement> result = dbChildren.Filter(value);
if (result.Count() > 1) throw new UnexpectedException("Duplicated.");
XElement dbChild = (result.Count() == 0) ? null : result.First();
return dbChild;
}
}
}
}
| 45.74
| 152
| 0.535986
|
[
"MIT"
] |
sundy39/xf
|
ElementFramework/Objects/Writer/ExecuteUnit.cs
| 11,437
|
C#
|
/*
********************************************************************
*
* 曹旭升(sheng.c)
* E-mail: cao.silhouette@msn.com
* QQ: 279060597
* https://github.com/iccb1013
* http://shengxunwei.com
*
* © Copyright 2016
*
********************************************************************/
using Linkup.DataRelationalMapping;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sheng.WeixinConstruction.Infrastructure
{
[Table("Movie")]
public class MovieEntity
{
private Guid _id = Guid.NewGuid();
public Guid Id
{
get { return _id; }
set { _id = value; }
}
public string Name
{
get;
set;
}
public string Image
{
get;
set;
}
/// <summary>
/// 导演
/// </summary>
public string Director
{
get;
set;
}
/// <summary>
/// 主演
/// </summary>
public string Actor
{
get;
set;
}
/// <summary>
/// 时长
/// </summary>
public string Time
{
get;
set;
}
/// <summary>
/// 类型:爱情/剧情/科幻
/// </summary>
public string Type
{
get;
set;
}
/// <summary>
/// 时光网ID
/// </summary>
public int MtimeId
{
get;
set;
}
private List<MovieTimesEntity> _timesList = new List<MovieTimesEntity>();
[NotMapped]
public List<MovieTimesEntity> TimesList
{
get { return _timesList; }
set { _timesList = value; }
}
private List<string> _showTypeList = null;
[NotMapped]
public List<string> ShowTypeList
{
get
{
if(_showTypeList==null)
{
_showTypeList = new List<string>();
foreach (var item in _timesList)
{
if (_showTypeList.Contains(item.ShowType) == false)
_showTypeList.Add(item.ShowType);
}
_showTypeList = _showTypeList.OrderBy((s) => { return s; }).ToList();
}
return _showTypeList;
}
}
}
}
| 21.008264
| 89
| 0.405586
|
[
"MIT"
] |
1002753959/Sheng.WeixinConstruction
|
SourceCode/Sheng.WeixinConstruction.Infrastructure/Movie/MovieEntity.cs
| 2,591
|
C#
|
using System.Text.Json.Serialization;
namespace MyChess.Interfaces;
public class User
{
[JsonPropertyName("id")]
public string ID { get; set; } = string.Empty;
[JsonPropertyName("name")]
public string Name { get; set; } = string.Empty;
}
| 20.769231
| 53
| 0.648148
|
[
"MIT"
] |
JanneMattila/chess
|
src/MyChess/Interfaces/User.cs
| 272
|
C#
|
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using Google.Api.Ads.AdManager.Lib;
using Google.Api.Ads.AdManager.Util.v201908;
using Google.Api.Ads.AdManager.v201908;
using System;
namespace Google.Api.Ads.AdManager.Examples.CSharp.v201908
{
/// <summary>
/// This example gets all CMS metadata keys.
/// </summary>
public class GetAllCmsMetadataKeys : SampleBase
{
/// <summary>
/// Returns a description about the code example.
/// </summary>
public override string Description
{
get { return "This example gets all CMS metadata keys."; }
}
/// <summary>
/// Main method, to run this code example as a standalone application.
/// </summary>
public static void Main()
{
GetAllCmsMetadataKeys codeExample = new GetAllCmsMetadataKeys();
Console.WriteLine(codeExample.Description);
try
{
codeExample.Run(new AdManagerUser());
}
catch (Exception e)
{
Console.WriteLine("Failed to get CMS metadata keys. Exception says \"{0}\"",
e.Message);
}
}
/// <summary>
/// Run the code example.
/// </summary>
public void Run(AdManagerUser user)
{
using (CmsMetadataService cmsMetadataService = user.GetService<CmsMetadataService>())
{
// Create a statement to select CMS metadata keys.
int pageSize = StatementBuilder.SUGGESTED_PAGE_LIMIT;
StatementBuilder statementBuilder =
new StatementBuilder().OrderBy("id ASC").Limit(pageSize);
// Retrieve a small amount of CMS metadata keys at a time, paging through until all
// CMS metadata keys have been retrieved.
int totalResultSetSize = 0;
do
{
CmsMetadataKeyPage page = cmsMetadataService.getCmsMetadataKeysByStatement(
statementBuilder.ToStatement());
// Print out some information for each CMS metadata key.
if (page.results != null)
{
totalResultSetSize = page.totalResultSetSize;
int i = page.startIndex;
foreach (CmsMetadataKey cmsMetadataKey in page.results)
{
Console.WriteLine(
"{0}) CMS metadata key with ID {1} and name \"{2}\" was found.",
i++, cmsMetadataKey.id, cmsMetadataKey.name);
}
}
statementBuilder.IncreaseOffsetBy(pageSize);
} while (statementBuilder.GetOffset() < totalResultSetSize);
Console.WriteLine("Number of results found: {0}", totalResultSetSize);
}
}
}
}
| 37.6
| 99
| 0.56523
|
[
"Apache-2.0"
] |
CoryLiseno/googleads-dotnet-lib
|
examples/AdManager/CSharp/v201908/CmsMetadataService/GetAllCmsMetadataKeys.cs
| 3,572
|
C#
|
namespace Compiler.Parsing.Parselets
{
public class NameParselet : IPrefixParselet
{
public IExpression Parse(Parser parser, Token token)
{
return new NameExpression(token.value);
}
}
}
| 23.3
| 60
| 0.635193
|
[
"MIT"
] |
Artmann/yay
|
Compiler/Parsing/Parselets/NameParselet.cs
| 233
|
C#
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.